Skip to content

Commit

Permalink
feat: implement dispatch msg
Browse files Browse the repository at this point in the history
  • Loading branch information
shiki-tak committed Feb 21, 2024
1 parent 9acaddc commit 0517834
Show file tree
Hide file tree
Showing 11 changed files with 318 additions and 44 deletions.
5 changes: 5 additions & 0 deletions docs/core/proto-docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -9183,6 +9183,11 @@ Contains the values needed to calculate "all inputs hash".



| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `results` | [bytes](#bytes) | repeated | |





Expand Down
4 changes: 3 additions & 1 deletion proto/finschia/zkauth/v1beta1/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ message MsgExecution {
ZKAuthSignature zk_auth_signature = 2 [(gogoproto.nullable) = false];
}

message MsgExecutionResponse {}
message MsgExecutionResponse {
repeated bytes results = 1;
}

message ZKAuthSignature {
ZKAuthInputs zk_auth_inputs = 1;
Expand Down
49 changes: 49 additions & 0 deletions x/zkauth/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ package cli

import (
"fmt"
"os"
"strconv"

"github.com/spf13/cobra"

"github.com/Finschia/finschia-sdk/client"
"github.com/Finschia/finschia-sdk/client/tx"
authclient "github.com/Finschia/finschia-sdk/x/auth/client"
"github.com/Finschia/finschia-sdk/x/zkauth/types"
)

Expand All @@ -19,5 +23,50 @@ func GetTxCmd() *cobra.Command {
RunE: client.ValidateCmd,
}

cmd.AddCommand(
NewCmdExecution(),
)

return cmd
}

func NewCmdExecution() *cobra.Command {
cmd := &cobra.Command{
Use: "execuion [tx_json_file] [zk_proof_json_file] [max_block_height]",
Short: "execute zkauth tx",
Long: "execute zkauth tx",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}

theTx, err := authclient.ReadTxFromFile(clientCtx, args[0])
if err != nil {
return err
}

var zkAuthInputs types.ZKAuthInputs
bytes, err := os.ReadFile(args[1])
if err != nil {
return err
}
clientCtx.Codec.UnmarshalInterfaceJSON(bytes, &zkAuthInputs)
maxBlockHeight, err := strconv.ParseUint(args[2], 10, 64)
if err != nil {
return err
}

zkAuthSign := types.ZKAuthSignature{
ZkAuthInputs: &zkAuthInputs,
MaxBlockHeight: maxBlockHeight,
}
msg := types.NewMsgExecution(theTx.GetMsgs(), zkAuthSign)

return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}

return cmd
}
46 changes: 46 additions & 0 deletions x/zkauth/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,81 @@ import (
"net/http"
"os"
"path/filepath"
"strconv"
"time"

"github.com/Finschia/finschia-sdk/baseapp"
"github.com/Finschia/finschia-sdk/codec"
storetypes "github.com/Finschia/finschia-sdk/store/types"
sdk "github.com/Finschia/finschia-sdk/types"
sdkerrors "github.com/Finschia/finschia-sdk/types/errors"
"github.com/Finschia/finschia-sdk/x/zkauth/types"
"github.com/Finschia/ostracon/libs/log"
abci "github.com/tendermint/tendermint/abci/types"
)

type Keeper struct {
cdc codec.BinaryCodec
storeKey storetypes.StoreKey
router *baseapp.MsgServiceRouter
}

func NewKeeper(
cdc codec.BinaryCodec,
storeKey storetypes.StoreKey,
router *baseapp.MsgServiceRouter,
) *Keeper {

return &Keeper{
cdc: cdc,
storeKey: storeKey,
router: router,
}
}

func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}

func (k Keeper) DispatchMsgs(ctx sdk.Context, msgs []sdk.Msg) ([][]byte, error) {
results := make([][]byte, len(msgs))

for i, msg := range msgs {
signers := msg.GetSigners()
if len(signers) != 1 {
return nil, sdkerrors.ErrInvalidRequest.Wrap("authorization can be given to msg with only one signer")
}

Check warning on line 53 in x/zkauth/keeper/keeper.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/keeper.go#L52-L53

Added lines #L52 - L53 were not covered by tests
if err := msg.ValidateBasic(); err != nil {
return nil, err
}

Check warning on line 56 in x/zkauth/keeper/keeper.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/keeper.go#L55-L56

Added lines #L55 - L56 were not covered by tests

handler := k.router.Handler(msg)
if handler == nil {
return nil, sdkerrors.ErrUnknownRequest.Wrapf("unrecognized message route: %s", sdk.MsgTypeURL(msg))
}

Check warning on line 61 in x/zkauth/keeper/keeper.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/keeper.go#L60-L61

Added lines #L60 - L61 were not covered by tests

msgResp, err := handler(ctx, msg)
if err != nil {
return nil, sdkerrors.Wrapf(err, "failed to execute message; message %v", msg)
}

Check warning on line 66 in x/zkauth/keeper/keeper.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/keeper.go#L65-L66

Added lines #L65 - L66 were not covered by tests

results[i] = msgResp.Data

events := msgResp.Events
sdkEvents := make([]sdk.Event, 0, len(events))
for _, event := range events {
e := event
e.Attributes = append(e.Attributes, abci.EventAttribute{Key: []byte("zkauth_msg_index"), Value: []byte(strconv.Itoa(i))})

sdkEvents = append(sdkEvents, sdk.Event(e))
}

ctx.EventManager().EmitEvents(sdkEvents)
}

return results, nil
}

func (k Keeper) FetchJWK(ctx sdk.Context, nodeHome string) {
logger := k.Logger(ctx)
var defaultZKAuthOAuthProviders = [1]types.OidcProvider{types.Google}
Expand Down
47 changes: 43 additions & 4 deletions x/zkauth/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import (
"testing"
"time"

"github.com/Finschia/finschia-sdk/simapp"
sdk "github.com/Finschia/finschia-sdk/types"
banktypes "github.com/Finschia/finschia-sdk/x/bank/types"
"github.com/Finschia/finschia-sdk/x/zkauth/testutil"
"github.com/Finschia/finschia-sdk/x/zkauth/types"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -53,7 +56,8 @@ func mockHandler(w http.ResponseWriter, r *http.Request) {
}

func TestGetJWK(t *testing.T) {
k, _ := testutil.ZkAuthKeeper(t)
testApp := testutil.ZkAuthKeeper(t)
k := testApp.Keeper
server := httptest.NewServer(http.HandlerFunc(mockHandler))
defer server.Close()

Expand All @@ -68,7 +72,8 @@ func TestGetJWK(t *testing.T) {
}

func TestParseJWKs(t *testing.T) {
k, _ := testutil.ZkAuthKeeper(t)
testApp := testutil.ZkAuthKeeper(t)
k := testApp.Keeper
server := httptest.NewServer(http.HandlerFunc(mockHandler))
defer server.Close()

Expand All @@ -86,8 +91,9 @@ func TestParseJWKs(t *testing.T) {
func TestFetchJwk(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(mockHandler))
defer server.Close()
k, ctx := testutil.ZkAuthKeeper(t)

testApp := testutil.ZkAuthKeeper(t)
k := testApp.Keeper
ctx := testApp.Ctx
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

Expand All @@ -108,3 +114,36 @@ func TestFetchJwk(t *testing.T) {
json.Unmarshal(content, &actualObj)
require.Equal(t, expectedObj, actualObj)
}

func TestDispatchMsgs(t *testing.T) {
testApp := testutil.ZkAuthKeeper(t)
app, k, ctx := testApp.Simapp, testApp.Keeper, testApp.Ctx

addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100))
fromAddr := addrs[0]
toAddr := addrs[1]

newCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 5))

bankMsg := banktypes.MsgSend{
Amount: newCoins,
FromAddress: fromAddr.String(),
ToAddress: toAddr.String(),
}

zkAuthSig := types.ZKAuthSignature{}

msgs := types.NewMsgExecution([]sdk.Msg{&bankMsg}, zkAuthSig)

execMsgs, err := msgs.GetMessages()
require.NoError(t, err)
result, err := k.DispatchMsgs(ctx, execMsgs)

require.NoError(t, err)
require.NotNil(t, result)

fromBalance := app.BankKeeper.GetBalance(ctx, fromAddr, "stake")
require.True(t, fromBalance.Equal(sdk.NewInt64Coin("stake", 95)))
toBalance := app.BankKeeper.GetBalance(ctx, toAddr, "stake")
require.True(t, toBalance.Equal(sdk.NewInt64Coin("stake", 105)))
}
15 changes: 14 additions & 1 deletion x/zkauth/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package keeper
import (
"context"

sdk "github.com/Finschia/finschia-sdk/types"
"github.com/Finschia/finschia-sdk/x/zkauth/types"
)

Expand All @@ -19,5 +20,17 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer {
var _ types.MsgServer = msgServer{}

func (k msgServer) Execution(goCtx context.Context, msg *types.MsgExecution) (*types.MsgExecutionResponse, error) {
return &types.MsgExecutionResponse{}, nil
ctx := sdk.UnwrapSDKContext(goCtx)

msgs, err := msg.GetMessages()
if err != nil {
return nil, err
}

Check warning on line 28 in x/zkauth/keeper/msg_server.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/msg_server.go#L27-L28

Added lines #L27 - L28 were not covered by tests

results, err := k.DispatchMsgs(ctx, msgs)
if err != nil {
return nil, err
}

Check warning on line 33 in x/zkauth/keeper/msg_server.go

View check run for this annotation

Codecov / codecov/patch

x/zkauth/keeper/msg_server.go#L32-L33

Added lines #L32 - L33 were not covered by tests

return &types.MsgExecutionResponse{Results: results}, nil
}
33 changes: 29 additions & 4 deletions x/zkauth/keeper/msg_server_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
package keeper_test

import (
"context"
"testing"

"github.com/Finschia/finschia-sdk/simapp"
sdk "github.com/Finschia/finschia-sdk/types"
banktypes "github.com/Finschia/finschia-sdk/x/bank/types"
"github.com/Finschia/finschia-sdk/x/zkauth/keeper"
datest "github.com/Finschia/finschia-sdk/x/zkauth/testutil"
"github.com/Finschia/finschia-sdk/x/zkauth/types"
"github.com/stretchr/testify/require"
)

func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) {
k, ctx := datest.ZkAuthKeeper(t)
return keeper.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx)
func setupMsgServer(t testing.TB) (types.MsgServer, *simapp.SimApp, sdk.Context) {
testApp := datest.ZkAuthKeeper(t)
k, ctx := testApp.Keeper, testApp.Ctx
return keeper.NewMsgServerImpl(*k), testApp.Simapp, ctx
}

func TestExecution(t *testing.T) {
msgServer, app, ctx := setupMsgServer(t)
newCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 5))
addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100))
fromAddr := addrs[0]
toAddr := addrs[1]

bankMsg := banktypes.MsgSend{
Amount: newCoins,
FromAddress: fromAddr.String(),
ToAddress: toAddr.String(),
}

zkAuthSig := types.ZKAuthSignature{}

msgs := types.NewMsgExecution([]sdk.Msg{&bankMsg}, zkAuthSig)

resp, err := msgServer.Execution(sdk.WrapSDKContext(ctx), msgs)
require.NoError(t, err)
require.NotNil(t, resp)
}
23 changes: 19 additions & 4 deletions x/zkauth/testutil/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package testutil
import (
"testing"

"github.com/Finschia/finschia-sdk/simapp"
"github.com/Finschia/finschia-sdk/x/zkauth/keeper"
"github.com/Finschia/finschia-sdk/x/zkauth/types"

"github.com/Finschia/ostracon/libs/log"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmdb "github.com/tendermint/tm-db"
Expand All @@ -18,7 +18,15 @@ import (
sdk "github.com/Finschia/finschia-sdk/types"
)

func ZkAuthKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
type TestApp struct {
Simapp *simapp.SimApp
Keeper *keeper.Keeper
Ctx sdk.Context
}

func ZkAuthKeeper(t testing.TB) TestApp {
checkTx := false
app := simapp.Setup(checkTx)
storeKey := sdk.NewKVStoreKey(types.StoreKey)
memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey)

Expand All @@ -34,9 +42,16 @@ func ZkAuthKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
k := keeper.NewKeeper(
cdc,
storeKey,
app.MsgServiceRouter(),
)

ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger())
ctx := app.BaseApp.NewContext(false, tmproto.Header{})

testApp := TestApp{
Simapp: app,
Keeper: k,
Ctx: ctx,
}

return k, ctx
return testApp
}
2 changes: 1 addition & 1 deletion x/zkauth/testutil/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import (
)

func TestKeeper(t *testing.T) {
_, _ = ZkAuthKeeper(t)
_ = ZkAuthKeeper(t)
}
Loading

0 comments on commit 0517834

Please sign in to comment.