Skip to content

Commit

Permalink
Merge pull request #1688 from mesg-foundation/feature/withdraw-coins
Browse files Browse the repository at this point in the history
Handle withdraw from resources
  • Loading branch information
antho1404 authored Mar 6, 2020
2 parents ca26c07 + 2a1df21 commit 101399d
Show file tree
Hide file tree
Showing 21 changed files with 365 additions and 59 deletions.
4 changes: 2 additions & 2 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,11 @@ func NewInitApp(
)

// Engine's module keepers
app.ownershipKeeper = ownership.NewKeeper(app.cdc, keys[ownership.StoreKey])
app.ownershipKeeper = ownership.NewKeeper(app.cdc, keys[ownership.StoreKey], app.bankKeeper)
app.instanceKeeper = instance.NewKeeper(app.cdc, keys[instance.StoreKey])
app.processKeeper = process.NewKeeper(app.cdc, keys[process.StoreKey], app.instanceKeeper, app.ownershipKeeper)
app.serviceKeeper = service.NewKeeper(app.cdc, keys[service.StoreKey], app.ownershipKeeper)
app.runnerKeeper = runner.NewKeeper(app.cdc, keys[runner.StoreKey], app.instanceKeeper)
app.runnerKeeper = runner.NewKeeper(app.cdc, keys[runner.StoreKey], app.instanceKeeper, app.ownershipKeeper)
app.executionKeeper = execution.NewKeeper(
app.cdc,
keys[execution.StoreKey],
Expand Down
3 changes: 2 additions & 1 deletion core/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/mesg-foundation/engine/server/grpc"
"github.com/mesg-foundation/engine/version"
"github.com/sirupsen/logrus"
rpcclient "github.com/tendermint/tendermint/rpc/client"
rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
tmtypes "github.com/tendermint/tendermint/types"
db "github.com/tendermint/tm-db"
Expand Down Expand Up @@ -186,7 +187,7 @@ func main() {
}()

// create cosmos client
client, err := cosmos.NewClient(node, cdc, kb, genesis.ChainID, cfg.Account.Name, cfg.Account.Password, cfg.Cosmos.MinGasPrices)
client, err := cosmos.NewClient(rpcclient.NewLocal(node), cdc, kb, genesis.ChainID, cfg.Account.Name, cfg.Account.Password, cfg.Cosmos.MinGasPrices)
if err != nil {
logrus.WithField("module", "main").Fatalln(err)
}
Expand Down
12 changes: 6 additions & 6 deletions cosmos/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@ import (
"github.com/mesg-foundation/engine/ext/xstrings"
"github.com/mesg-foundation/engine/hash"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/node"
rpcclient "github.com/tendermint/tendermint/rpc/client"
tenderminttypes "github.com/tendermint/tendermint/types"
)

// Client is a tendermint client with helper functions.
type Client struct {
*rpcclient.Local
rpcclient.Client
cdc *codec.Codec
kb keys.Keybase
chainID string
Expand All @@ -41,13 +40,13 @@ type Client struct {
}

// NewClient returns a rpc tendermint client.
func NewClient(node *node.Node, cdc *codec.Codec, kb keys.Keybase, chainID, accName, accPassword, minGasPrices string) (*Client, error) {
func NewClient(client rpcclient.Client, cdc *codec.Codec, kb keys.Keybase, chainID, accName, accPassword, minGasPrices string) (*Client, error) {
minGasPricesDecoded, err := sdktypes.ParseDecCoins(minGasPrices)
if err != nil {
return nil, err
}
return &Client{
Local: rpcclient.NewLocal(node),
Client: client,
cdc: cdc,
kb: kb,
chainID: chainID,
Expand Down Expand Up @@ -93,7 +92,7 @@ func (c *Client) QueryWithData(path string, data []byte) ([]byte, int64, error)
// BuildAndBroadcastMsg builds and signs message and broadcast it to node.
func (c *Client) BuildAndBroadcastMsg(msg sdktypes.Msg) (*abci.ResponseDeliverTx, error) {
c.broadcastMutex.Lock() // Lock the whole signature + broadcast of the transaction
signedTx, err := c.createAndSignTx([]sdktypes.Msg{msg})
signedTx, err := c.CreateAndSignTx([]sdktypes.Msg{msg})
if err != nil {
c.broadcastMutex.Unlock()
return nil, err
Expand Down Expand Up @@ -204,7 +203,8 @@ func (c *Client) GetAccount() (authExported.Account, error) {
return c.acc, nil
}

func (c *Client) createAndSignTx(msgs []sdktypes.Msg) (tenderminttypes.Tx, error) {
// CreateAndSignTx build and sign a msg with client account.
func (c *Client) CreateAndSignTx(msgs []sdktypes.Msg) (tenderminttypes.Tx, error) {
// retrieve account
accR, err := c.GetAccount()
if err != nil {
Expand Down
33 changes: 28 additions & 5 deletions e2e/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@ import (
"context"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"testing"

"github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/mesg-foundation/engine/app"
"github.com/mesg-foundation/engine/config"
"github.com/mesg-foundation/engine/cosmos"
pb "github.com/mesg-foundation/engine/protobuf/api"
"github.com/stretchr/testify/require"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"google.golang.org/grpc"
)

Expand All @@ -27,8 +31,9 @@ type apiclient struct {
}

var (
client apiclient
cdc = app.MakeCodec()
client apiclient
cclient *cosmos.Client
cdc = app.MakeCodec()
)

const (
Expand Down Expand Up @@ -70,14 +75,32 @@ func TestAPI(t *testing.T) {
}

cfg, err := config.New()
if err != nil {
panic(err)
}
require.NoError(t, err)

cosmos.CustomizeConfig(cfg)

conn, err := grpc.DialContext(context.Background(), "localhost:50052", grpc.WithInsecure())
require.NoError(t, err)

// change and recreate cosmos relative path because CI dir permissions
cfg.Cosmos.RelativePath = "e2e.cosmos"
err = os.MkdirAll(filepath.Join(cfg.Path, cfg.Cosmos.RelativePath), os.FileMode(0755))
require.NoError(t, err)

kb, err := cosmos.NewKeybase(filepath.Join(cfg.Path, cfg.Cosmos.RelativePath))
require.NoError(t, err)
if cfg.Account.Mnemonic != "" {
_, err = kb.CreateAccount(cfg.Account.Name, cfg.Account.Mnemonic, "", cfg.Account.Password, keys.CreateHDPath(cfg.Account.Number, cfg.Account.Index).String(), cosmos.DefaultAlgo)
require.NoError(t, err)
}

httpclient, err := rpcclient.NewHTTP("http://localhost:26657", "/websocket")
require.NoError(t, err)
require.NoError(t, httpclient.Start())
defer httpclient.Stop()
cclient, err = cosmos.NewClient(httpclient, cdc, kb, cfg.DevGenesis.ChainID, cfg.Account.Name, cfg.Account.Password, cfg.Cosmos.MinGasPrices)
require.NoError(t, err)

client = apiclient{
pb.NewServiceClient(conn),
pb.NewEventClient(conn),
Expand Down
28 changes: 28 additions & 0 deletions e2e/execution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import (
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/mesg-foundation/engine/execution"
"github.com/mesg-foundation/engine/hash"
"github.com/mesg-foundation/engine/protobuf/acknowledgement"
pb "github.com/mesg-foundation/engine/protobuf/api"
"github.com/mesg-foundation/engine/protobuf/types"
"github.com/mesg-foundation/engine/x/ownership"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto"
)
Expand Down Expand Up @@ -254,6 +256,32 @@ func testExecution(t *testing.T) {
lcdGet(t, "bank/balances/"+execAddress.String(), &coins)
require.True(t, coins.AmountOf("atto").Equal(sdk.NewInt(0)))
})

t.Run("withdraw from service", func(t *testing.T) {
acc, err := cclient.GetAccount()
require.NoError(t, err)
coins := sdk.NewCoins(sdk.NewCoin("atto", sdk.NewInt(7000)))
msg := ownership.NewMsgWithdrawCoins(testServiceHash, coins, acc.GetAddress())
_, err = cclient.BuildAndBroadcastMsg(msg)
require.NoError(t, err)

param := bank.NewQueryBalanceParams(sdk.AccAddress(crypto.AddressHash(testServiceHash)))
require.NoError(t, cclient.QueryJSON("custom/bank/balances", param, &coins))
require.True(t, coins.IsZero(), coins)
})

t.Run("withdraw from runner", func(t *testing.T) {
acc, err := cclient.GetAccount()
require.NoError(t, err)
coins := sdk.NewCoins(sdk.NewCoin("atto", sdk.NewInt(63000)))
msg := ownership.NewMsgWithdrawCoins(testRunnerHash, coins, acc.GetAddress())
_, err = cclient.BuildAndBroadcastMsg(msg)
require.NoError(t, err)

param := bank.NewQueryBalanceParams(sdk.AccAddress(crypto.AddressHash(testRunnerHash)))
require.NoError(t, cclient.QueryJSON("custom/bank/balances", param, &coins))
require.True(t, coins.IsZero(), coins)
})
})

t.Run("many executions in parallel", func(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions e2e/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,12 @@ func testProcess(t *testing.T) {
t.Run("lcd", func(t *testing.T) {
ownerships := make([]*ownership.Ownership, 0)
lcdGet(t, "ownership/list", &ownerships)
require.Len(t, ownerships, 1)
require.Len(t, ownerships, 2)
})
t.Run("grpc", func(t *testing.T) {
ownerships, err := client.OwnershipClient.List(context.Background(), &pb.ListOwnershipRequest{})
require.NoError(t, err)
require.Len(t, ownerships.Ownerships, 1)
require.Len(t, ownerships.Ownerships, 2)
})
})
}
11 changes: 11 additions & 0 deletions e2e/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ func testRunner(t *testing.T) {
require.NoError(t, err)
})

t.Run("recreate", func(t *testing.T) {
_, err := client.RunnerClient.Delete(context.Background(), &pb.DeleteRunnerRequest{Hash: testRunnerHash})
require.NoError(t, err)
resp, err := client.RunnerClient.Create(context.Background(), &pb.CreateRunnerRequest{
ServiceHash: testServiceHash,
Env: []string{"BAR=3", "REQUIRED=4"},
})
require.NoError(t, err)
testRunnerHash = resp.Hash
})

t.Run("get", func(t *testing.T) {
t.Run("grpc", func(t *testing.T) {
resp, err := client.RunnerClient.Get(context.Background(), &pb.GetRunnerRequest{Hash: testRunnerHash})
Expand Down
47 changes: 25 additions & 22 deletions ownership/ownership.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions protobuf/types/ownership.proto
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ message Ownership {
None = 0;
Service = 1;
Process = 2;
Runner = 3;
}

// Resource's type.
Expand Down
2 changes: 1 addition & 1 deletion x/execution/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func NewHandler(k Keeper) sdk.Handler {
}
}

// handleMsgCreateExecution creates a new process.
// handleMsgCreateExecution creates a new execution.
func handleMsgCreateExecution(ctx sdk.Context, k Keeper, msg MsgCreateExecution) (*sdk.Result, error) {
s, err := k.Create(ctx, msg)
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions x/ownership/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ var (

ModuleCdc = types.ModuleCdc
QueryListOwnerships = types.QueryListOwnerships

NewMsgWithdrawCoins = types.NewMsgWithdrawCoins
)

// module types
type (
Keeper = keeper.Keeper
GenesisState = types.GenesisState
Params = types.Params

MsgWithdrawCoins = types.MsgWithdrawCoins
)
43 changes: 41 additions & 2 deletions x/ownership/client/cli/tx.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package cli

import (
"bufio"
"fmt"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"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/mesg-foundation/engine/hash"
"github.com/mesg-foundation/engine/x/ownership/internal/types"
"github.com/spf13/cobra"
)
Expand All @@ -20,7 +26,40 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command {
RunE: client.ValidateCmd,
}

ownershipTxCmd.AddCommand(flags.PostCommands()...)

ownershipTxCmd.AddCommand(flags.PostCommands(
GetCmdWithdrawCoins(cdc),
)...)
return ownershipTxCmd
}

// GetCmdWithdrawCoins is the CLI command for sending a WithdrawCoins transaction
func GetCmdWithdrawCoins(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "withdraw-coins [resource] [amount]",
Short: "withdraw amount from resource address",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
cliCtx := context.NewCLIContext().WithCodec(cdc)

txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))

h, err := hash.Decode(args[0])
if err != nil {
return err
}

coins, err := sdk.ParseCoins(args[1])
if err != nil {
return err
}

msg := types.NewMsgWithdrawCoins(h, coins, cliCtx.GetFromAddress())
if err = msg.ValidateBasic(); err != nil {
return err
}

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

0 comments on commit 101399d

Please sign in to comment.