Skip to content

Commit

Permalink
Merge pull request #4 from regen-friends/msg_internal
Browse files Browse the repository at this point in the history
Msg internal
  • Loading branch information
anilcse authored Dec 16, 2019
2 parents 425b1bd + a92593f commit f9d03fb
Show file tree
Hide file tree
Showing 8 changed files with 257 additions and 23 deletions.
3 changes: 3 additions & 0 deletions x/msg_authorization/client/cli/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package cli

const FlagExpiration = "expiration"
83 changes: 79 additions & 4 deletions x/msg_authorization/client/cli/tx.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
package cli

import (
"bufio"
"time"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
"github.com/cosmos/cosmos-sdk/x/msg_authorization/internal/types"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// GetTxCmd returns the transaction commands for this module
func GetTxCmd(cdc *codec.Codec) *cobra.Command {
AuthorizationTxCmd := &cobra.Command{
Use: types.ModuleName,
Short: "Authorization transactions subcommands",
Long: "Authorize and revoke access to execute transactions on behalf of your address",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
Expand All @@ -26,11 +35,77 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command {
}

func GetCmdGrantCapability(cdc *codec.Codec) *cobra.Command {
//TODO
return nil
cmd := &cobra.Command{
Use: "grant",
Short: "Grant authorization to an address",
Long: "Grant authorization to an address to execute a transaction on your behalf",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))
cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc)

granter := cliCtx.FromAddress
grantee, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
return err
}

var capability types.Capability
err = cdc.UnmarshalJSON([]byte(args[1]), &capability)
if err != nil {
return err
}
expirationString := viper.GetString(FlagExpiration)
expiration, err := time.Parse(time.RFC3339, expirationString)
if err != nil {
return err
}

msg := types.NewMsgGrantAuthorization(granter, grantee, capability, expiration)
if err := msg.ValidateBasic(); err != nil {
return err
}

return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, []sdk.Msg{msg})

},
}
cmd.Flags().String(FlagExpiration, "9999-12-31 23:59:59.52Z", "The time upto which the authorization is active for the user")

return cmd
}

func GetCmdRevokeCapability(cdc *codec.Codec) *cobra.Command {
//TODO
return nil
cmd := &cobra.Command{
Use: "revoke",
Short: "revoke authorization",
Long: "revoke authorization from an address for a transaction",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))
cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc)

granter := cliCtx.FromAddress
grantee, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
return err
}

var msgAuthorized sdk.Msg
err = cdc.UnmarshalJSON([]byte(args[1]), &msgAuthorized)
if err != nil {
return err
}

msg := types.NewMsgRevokeAuthorization(granter, grantee, msgAuthorized)
if err := msg.ValidateBasic(); err != nil {
return err
}

return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, []sdk.Msg{msg})
},
}
return cmd
}
23 changes: 21 additions & 2 deletions x/msg_authorization/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)

func NewHandler(k Keeper) sdk.Handler {
Expand All @@ -24,12 +25,30 @@ func NewHandler(k Keeper) sdk.Handler {
}

func handleMsgGrantAuthorization(ctx sdk.Context, msg MsgGrantAuthorization, k Keeper) sdk.Result {
//TODO
k.Grant(ctx, msg.Grantee, msg.Granter, msg.Capability, msg.Expiration)

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, msg.Granter.String()),
),
)

return sdk.Result{Events: ctx.EventManager().Events()}
}

func handleMsgRevokeAuthorization(ctx sdk.Context, msg MsgRevokeAuthorization, k Keeper) sdk.Result {
//TODO
k.Revoke(ctx, msg.Grantee, msg.Granter, msg.CapabilityMsgType)

ctx.EventManager().EmitEvent(
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, msg.Granter.String()),
),
)

return sdk.Result{Events: ctx.EventManager().Events()}
}

Expand Down
78 changes: 77 additions & 1 deletion x/msg_authorization/internal/keeper/keeper_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,77 @@
package keeper_test
package keeper

import (
"testing"
"time"

"github.com/stretchr/testify/suite"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/msg_authorization/internal/types"
"github.com/cosmos/cosmos-sdk/x/params"
)

type TestSuite struct {
suite.Suite
ctx sdk.Context
accountKeeper auth.AccountKeeper
paramsKeeper params.Keeper
bankKeeper bank.Keeper
keeper Keeper
router sdk.Router
}

func (s *TestSuite) SetupTest() {
s.ctx, s.accountKeeper, s.paramsKeeper, s.bankKeeper, s.keeper, s.router = SetupTestInput()

}

func (s *TestSuite) TestKeeper() {
err := s.bankKeeper.SetCoins(s.ctx, granterAddr, sdk.NewCoins(sdk.NewInt64Coin("steak", 10000)))
s.Require().Nil(err)
s.Require().True(s.bankKeeper.GetCoins(s.ctx, granterAddr).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("steak", 10000))))

s.T().Log("Verify that no capability returns nil")
capability, _ := s.keeper.GetCapability(s.ctx, granteeAddr, granterAddr, bank.MsgSend{})
s.Require().Nil(capability)
//require.Nil(t, expiration)
now := s.ctx.BlockHeader().Time
s.Require().NotNil(now)

newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100))
s.T().Log("Verify if expired capability is rejected")
s.keeper.Grant(s.ctx, granterAddr, granteeAddr, types.SendCapability{SpendLimit: newCoins}, now.Add(-1*time.Hour))
capability, _ = s.keeper.GetCapability(s.ctx, granteeAddr, granterAddr, bank.MsgSend{})
s.Require().Nil(capability)

s.T().Log("Verify if capability is accepted")
s.keeper.Grant(s.ctx, granteeAddr, granterAddr, types.SendCapability{SpendLimit: newCoins}, now.Add(time.Hour))
capability, _ = s.keeper.GetCapability(s.ctx, granteeAddr, granterAddr, bank.MsgSend{})
s.Require().NotNil(capability)
s.Require().Equal(capability.MsgType(), bank.MsgSend{})

s.T().Log("Verify fetching capability with wrong msg type fails")
capability, _ = s.keeper.GetCapability(s.ctx, granteeAddr, granterAddr, bank.MsgMultiSend{})
s.Require().Nil(capability)

s.T().Log("Verify fetching capability with wrong grantee fails")
capability, _ = s.keeper.GetCapability(s.ctx, recepientAddr, granterAddr, bank.MsgMultiSend{})
s.Require().Nil(capability)

s.T().Log("Verify revoke fails with wrong information")
s.keeper.Revoke(s.ctx, recepientAddr, granterAddr, bank.MsgSend{})
capability, _ = s.keeper.GetCapability(s.ctx, recepientAddr, granterAddr, bank.MsgSend{})
s.Require().Nil(capability)

s.T().Log("Verify revoke executes with correct information")
s.keeper.Revoke(s.ctx, recepientAddr, granterAddr, bank.MsgSend{})
capability, _ = s.keeper.GetCapability(s.ctx, granteeAddr, granterAddr, bank.MsgSend{})
s.Require().NotNil(capability)

}

func TestTestSuite(t *testing.T) {
suite.Run(t, new(TestSuite))
}
73 changes: 57 additions & 16 deletions x/msg_authorization/internal/keeper/test_common.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,38 @@
package keeper

import (
"time"

"github.com/tendermint/tendermint/crypto/ed25519"

abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/msg_authorization/internal/types"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply"
)

type testInput struct {
cdc *codec.Codec
ctx sdk.Context
ak auth.AccountKeeper
pk params.Keeper
bk bank.Keeper
dk Keeper
router sdk.Router
}
func makeTestCodec() *codec.Codec {
var cdc = codec.New()
auth.RegisterCodec(cdc)
types.RegisterCodec(cdc)
supply.RegisterCodec(cdc)
staking.RegisterCodec(cdc)
sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc)

func setupTestInput() testInput {
return cdc
}
func SetupTestInput() (sdk.Context, auth.AccountKeeper, params.Keeper, bank.BaseKeeper, Keeper, sdk.Router) {
db := dbm.NewMemDB()

cdc := codec.New()
Expand All @@ -31,13 +41,44 @@ func setupTestInput() testInput {
sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc)

//TODO create test input
return testInput{}
keyAcc := sdk.NewKVStoreKey(auth.StoreKey)
keyParams := sdk.NewKVStoreKey(params.StoreKey)
keyAuthorization := sdk.NewKVStoreKey(types.StoreKey)
tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey)

ms := store.NewCommitMultiStore(db)
ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyAuthorization, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db)

ms.LoadLatestVersion()

ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewNopLogger())
cdc = makeTestCodec()

blacklistedAddrs := make(map[string]bool)

paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace)
authKeeper := auth.NewAccountKeeper(cdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
bankKeeper := bank.NewBaseKeeper(authKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs)
bankKeeper.SetSendEnabled(ctx, true)

router := baseapp.NewRouter()
router.AddRoute("bank", bank.NewHandler(bankKeeper))

authorizationKeeper := NewKeeper(keyAuthorization, cdc, router)

authKeeper.SetParams(ctx, auth.DefaultParams())

return ctx, authKeeper, paramsKeeper, bankKeeper, authorizationKeeper, router
}

var (
senderPub = ed25519.GenPrivKey().PubKey()
recipientPub = ed25519.GenPrivKey().PubKey()
senderAddr = sdk.AccAddress(senderPub.Address())
recipientAddr = sdk.AccAddress(recipientPub.Address())
granteePub = ed25519.GenPrivKey().PubKey()
granterPub = ed25519.GenPrivKey().PubKey()
recepientPub = ed25519.GenPrivKey().PubKey()
granteeAddr = sdk.AccAddress(granteePub.Address())
granterAddr = sdk.AccAddress(granterPub.Address())
recepientAddr = sdk.AccAddress(recepientPub.Address())
)
4 changes: 4 additions & 0 deletions x/msg_authorization/internal/types/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgGrantAuthorization{}, "cosmos-sdk/GrantAuthorization", nil)
cdc.RegisterConcrete(MsgRevokeAuthorization{}, "cosmos-sdk/RevokeAuthorization", nil)
cdc.RegisterConcrete(MsgExecDelegated{}, "cosmos-sdk/ExecDelegated", nil)
cdc.RegisterConcrete(SendCapability{}, "cosmos-sdk/SendCapability", nil)
cdc.RegisterConcrete(CapabilityGrant{}, "cosmos-sdk/CapabilityGrant", nil)

cdc.RegisterInterface((*Capability)(nil), nil)
}
13 changes: 13 additions & 0 deletions x/msg_authorization/internal/types/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package types

// msg_authorization module events
const (
EventGrantAuthorization = "grant-authorization"
EventRevokeAuthorization = "revoke-authorization"
EventExecuteAuthorization = "execute-authorization"

AttributeKeyGranteeAddress = "grantee"
AttributeKeyGranterAddress = "granter"

AttributeValueCategory = ModuleName
)
3 changes: 3 additions & 0 deletions x/msg_authorization/test_common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package msg_authorization

//TODO create a mock app to demonstrate msg_authorization functionality

0 comments on commit f9d03fb

Please sign in to comment.