-
Notifications
You must be signed in to change notification settings - Fork 123
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
Add support for broadcasting arbitrary messages as test users #186
Changes from 7 commits
8e3d1f4
334194f
1e9d3a4
b175fbd
f35ea95
29be35c
23a0c8e
ea93673
0a1c16c
eb2ddb9
27bfe96
6edb295
4ce4b0f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package broadcast | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/cosmos/cosmos-sdk/client" | ||
"github.com/cosmos/cosmos-sdk/client/tx" | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
) | ||
|
||
type ClientContextOpt func(clientContext client.Context) client.Context | ||
|
||
type FactoryOpt func(factory tx.Factory) tx.Factory | ||
|
||
type User interface { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. After moving to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if we are in the |
||
GetKeyName() string | ||
Bech32Address(bech32Prefix string) string | ||
} | ||
|
||
// Broadcaster implementations can broadcast messages as the provided user. | ||
type Broadcaster interface { | ||
ConfigureFactoryOptions(opts ...FactoryOpt) | ||
ConfigureClientContextOptions(opts ...ClientContextOpt) | ||
GetFactory(ctx context.Context, user User) (tx.Factory, error) | ||
GetClientContext(ctx context.Context, user User) (client.Context, error) | ||
GetTxResponseBytes(ctx context.Context, user User) ([]byte, error) | ||
UnmarshalTxResponseBytes(ctx context.Context, bytes []byte) (sdk.TxResponse, error) | ||
} | ||
|
||
// Tx uses the provided Broadcaster to broadcast all the provided messages which will be signed | ||
// by the User provided. The sdk.TxResponse and an error are returned. | ||
func Tx(ctx context.Context, broadcaster Broadcaster, broadcastingUser User, msgs ...sdk.Msg) (sdk.TxResponse, error) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And this function can be named |
||
for _, msg := range msgs { | ||
if err := msg.ValidateBasic(); err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
} | ||
|
||
f, err := broadcaster.GetFactory(ctx, broadcastingUser) | ||
if err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
|
||
cc, err := broadcaster.GetClientContext(ctx, broadcastingUser) | ||
if err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
|
||
if err := tx.BroadcastTx(cc, f, msgs...); err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
|
||
txBytes, err := broadcaster.GetTxResponseBytes(ctx, broadcastingUser) | ||
if err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
|
||
return broadcaster.UnmarshalTxResponseBytes(ctx, txBytes) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
package cosmos | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/cosmos/cosmos-sdk/client" | ||
"github.com/cosmos/cosmos-sdk/client/flags" | ||
"github.com/cosmos/cosmos-sdk/client/tx" | ||
"github.com/cosmos/cosmos-sdk/crypto/keyring" | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
"github.com/cosmos/cosmos-sdk/types/tx/signing" | ||
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" | ||
"github.com/strangelove-ventures/ibctest/broadcast" | ||
"github.com/strangelove-ventures/ibctest/internal/dockerutil" | ||
) | ||
|
||
var _ broadcast.Broadcaster = &Broadcaster{} | ||
|
||
type Broadcaster struct { | ||
// buf stores the output sdk.TxResponse when broadcast.Tx is invoked. | ||
buf *bytes.Buffer | ||
// keyrings is a mapping of keyrings which point to a temporary test directory. The contents | ||
// of this directory are copied from the node container for the specific user. | ||
keyrings map[broadcast.User]keyring.Keyring | ||
|
||
// chain is a reference to the CosmosChain instance which will be the target of the messages. | ||
chain *CosmosChain | ||
// t is the testing.T for the current test. | ||
t *testing.T | ||
|
||
// factoryOptions is a slice of broadcast.FactoryOpt which enables arbitrary configuration of the tx.Factory. | ||
factoryOptions []broadcast.FactoryOpt | ||
// clientContextOptions is a slice of broadcast.ClientContextOpt which enables arbitrary configuration of the client.Context. | ||
clientContextOptions []broadcast.ClientContextOpt | ||
} | ||
|
||
// NewBroadcaster returns a instance of Broadcaster which can be used with broadcast.Tx to | ||
// broadcast messages sdk messages. | ||
func NewBroadcaster(t *testing.T, chain *CosmosChain) *Broadcaster { | ||
return &Broadcaster{ | ||
t: t, | ||
chain: chain, | ||
buf: &bytes.Buffer{}, | ||
keyrings: map[broadcast.User]keyring.Keyring{}, | ||
} | ||
} | ||
|
||
// ConfigureFactoryOptions ensure the given configuration functions are run when calling GetFactory | ||
// after all default options have been applied. | ||
func (b *Broadcaster) ConfigureFactoryOptions(opts ...broadcast.FactoryOpt) { | ||
b.factoryOptions = append(b.factoryOptions, opts...) | ||
} | ||
|
||
// ConfigureClientContextOptions ensure the given configuration functions are run when calling GetClientContext | ||
// after all default options have been applied. | ||
func (b *Broadcaster) ConfigureClientContextOptions(opts ...broadcast.ClientContextOpt) { | ||
b.clientContextOptions = append(b.clientContextOptions, opts...) | ||
} | ||
|
||
// GetFactory returns an instance of tx.Factory that is configured with this Broadcaster's CosmosChain | ||
// and the provided user. | ||
func (b *Broadcaster) GetFactory(ctx context.Context, user broadcast.User) (tx.Factory, error) { | ||
clientContext, err := b.GetClientContext(ctx, user) | ||
if err != nil { | ||
return tx.Factory{}, err | ||
} | ||
|
||
sdkAdd, err := sdk.AccAddressFromBech32(user.Bech32Address(b.chain.Config().Bech32Prefix)) | ||
if err != nil { | ||
return tx.Factory{}, err | ||
} | ||
|
||
accNumber, err := clientContext.AccountRetriever.GetAccount(clientContext, sdkAdd) | ||
if err != nil { | ||
return tx.Factory{}, err | ||
} | ||
|
||
f := b.defaultTxFactory(clientContext, accNumber.GetAccountNumber()) | ||
for _, opt := range b.factoryOptions { | ||
f = opt(f) | ||
} | ||
return f, nil | ||
} | ||
|
||
// GetClientContext returns a client context that is configured with this Broadcaster's CosmosChain and | ||
// the provided user. | ||
func (b *Broadcaster) GetClientContext(ctx context.Context, user broadcast.User) (client.Context, error) { | ||
chain := b.chain | ||
cn := chain.getFullNode() | ||
|
||
_, ok := b.keyrings[user] | ||
if !ok { | ||
localDir := b.t.TempDir() | ||
containerKeyringDir := fmt.Sprintf("%s/keyring-test", cn.NodeHome()) | ||
kr, err := dockerutil.NewLocalKeyringFromDockerContainer(ctx, cn.Pool.Client, localDir, containerKeyringDir, cn.Container.ID) | ||
if err != nil { | ||
return client.Context{}, err | ||
} | ||
b.keyrings[user] = kr | ||
} | ||
|
||
sdkAdd, err := sdk.AccAddressFromBech32(user.Bech32Address(chain.Config().Bech32Prefix)) | ||
if err != nil { | ||
return client.Context{}, err | ||
} | ||
|
||
clientContext := b.defaultClientContext(user, sdkAdd) | ||
for _, opt := range b.clientContextOptions { | ||
clientContext = opt(clientContext) | ||
} | ||
return clientContext, nil | ||
} | ||
|
||
// GetTxResponseBytes returns the sdk.TxResponse bytes which returned from broadcast.Tx. | ||
func (b *Broadcaster) GetTxResponseBytes(ctx context.Context, user broadcast.User) ([]byte, error) { | ||
if b.buf == nil || b.buf.Len() == 0 { | ||
return nil, fmt.Errorf("empty buffer, transaction has not be executed yet") | ||
} | ||
return b.buf.Bytes(), nil | ||
} | ||
|
||
// UnmarshalTxResponseBytes accepts the sdk.TxResponse bytes and unmarshalls them into an | ||
// instance of sdk.TxResponse. | ||
func (b *Broadcaster) UnmarshalTxResponseBytes(ctx context.Context, bytes []byte) (sdk.TxResponse, error) { | ||
resp := sdk.TxResponse{} | ||
if err := defaultEncoding.Marshaler.UnmarshalJSON(bytes, &resp); err != nil { | ||
return sdk.TxResponse{}, err | ||
} | ||
return resp, nil | ||
} | ||
|
||
// defaultClientContext returns a default client context configured with the user as the sender. | ||
func (b *Broadcaster) defaultClientContext(fromUser broadcast.User, sdkAdd sdk.AccAddress) client.Context { | ||
// initialize a clean buffer each time | ||
b.buf = &bytes.Buffer{} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should probably be |
||
kr := b.keyrings[fromUser] | ||
cn := b.chain.getFullNode() | ||
return cn.CliContext(). | ||
WithOutput(b.buf). | ||
WithFrom(fromUser.Bech32Address(b.chain.Config().Bech32Prefix)). | ||
WithFromAddress(sdkAdd). | ||
WithFromName(fromUser.GetKeyName()). | ||
WithSkipConfirmation(true). | ||
WithAccountRetriever(authtypes.AccountRetriever{}). | ||
WithKeyring(kr). | ||
WithBroadcastMode(flags.BroadcastBlock). | ||
WithCodec(defaultEncoding.Marshaler). | ||
WithHomeDir(cn.Home) | ||
|
||
} | ||
|
||
// defaultTxFactory creates a new Factory with default configuration. | ||
func (b *Broadcaster) defaultTxFactory(clientCtx client.Context, accountNumber uint64) tx.Factory { | ||
chainConfig := b.chain.Config() | ||
return tx.Factory{}. | ||
WithAccountNumber(accountNumber). | ||
WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). | ||
WithGasAdjustment(chainConfig.GasAdjustment). | ||
WithGas(flags.DefaultGasLimit). | ||
WithGasPrices(chainConfig.GasPrices). | ||
WithMemo("ibctest"). | ||
WithTxConfig(clientCtx.TxConfig). | ||
WithAccountRetriever(clientCtx.AccountRetriever). | ||
WithKeybase(clientCtx.Keyring). | ||
WithChainID(clientCtx.ChainID). | ||
WithSimulateAndExecute(false) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,18 +3,24 @@ package ibctest_test | |
import ( | ||
"context" | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/cosmos/cosmos-sdk/crypto/hd" | ||
"github.com/cosmos/cosmos-sdk/crypto/keyring" | ||
"github.com/cosmos/cosmos-sdk/types" | ||
"testing" | ||
|
||
"github.com/strangelove-ventures/ibctest" | ||
"github.com/strangelove-ventures/ibctest/broadcast" | ||
"github.com/strangelove-ventures/ibctest/chain/cosmos" | ||
"github.com/strangelove-ventures/ibctest/ibc" | ||
"github.com/strangelove-ventures/ibctest/relayer/rly" | ||
"github.com/strangelove-ventures/ibctest/test" | ||
"github.com/strangelove-ventures/ibctest/testreporter" | ||
"github.com/stretchr/testify/require" | ||
"go.uber.org/zap" | ||
"go.uber.org/zap/zaptest" | ||
|
||
transfertypes "github.com/cosmos/ibc-go/v3/modules/apps/transfer/types" | ||
clienttypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types" | ||
) | ||
|
||
func TestInterchain_DuplicateChain(t *testing.T) { | ||
|
@@ -197,7 +203,7 @@ func TestInterchain_CreateUser(t *testing.T) { | |
require.NotEmpty(t, mnemonic) | ||
|
||
user := ibctest.GetAndFundTestUserWithMnemonic(t, ctx, keyName, mnemonic, 10000, gaia0) | ||
|
||
require.NoError(t, test.WaitForBlocks(ctx, 2, gaia0)) | ||
require.NotEmpty(t, user.Address) | ||
require.NotEmpty(t, user.KeyName) | ||
|
||
|
@@ -210,6 +216,7 @@ func TestInterchain_CreateUser(t *testing.T) { | |
t.Run("without mnemonic", func(t *testing.T) { | ||
keyName := "regular-user-name" | ||
users := ibctest.GetAndFundTestUsers(t, ctx, keyName, 10000, gaia0) | ||
require.NoError(t, test.WaitForBlocks(ctx, 2, gaia0)) | ||
require.Len(t, users, 1) | ||
require.NotEmpty(t, users[0].Address) | ||
require.NotEmpty(t, users[0].KeyName) | ||
|
@@ -220,6 +227,71 @@ func TestInterchain_CreateUser(t *testing.T) { | |
}) | ||
} | ||
|
||
func TestCosmosChain_BroadcastTx(t *testing.T) { | ||
if testing.Short() { | ||
t.Skip("skipping in short mode") | ||
} | ||
|
||
t.Parallel() | ||
|
||
home := ibctest.TempDir(t) | ||
pool, network := ibctest.DockerSetup(t) | ||
|
||
cf := ibctest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*ibctest.ChainSpec{ | ||
// Two otherwise identical chains that only differ by ChainID. | ||
{Name: "gaia", ChainName: "g1", Version: "v7.0.1", ChainConfig: ibc.ChainConfig{ChainID: "cosmoshub-0"}}, | ||
{Name: "gaia", ChainName: "g2", Version: "v7.0.1", ChainConfig: ibc.ChainConfig{ChainID: "cosmoshub-1"}}, | ||
}) | ||
|
||
chains, err := cf.Chains(t.Name()) | ||
require.NoError(t, err) | ||
|
||
gaia0, gaia1 := chains[0], chains[1] | ||
|
||
r := ibctest.NewBuiltinRelayerFactory(ibc.CosmosRly, zaptest.NewLogger(t)).Build( | ||
t, pool, network, home, | ||
) | ||
|
||
ic := ibctest.NewInterchain(). | ||
AddChain(gaia0). | ||
AddChain(gaia1). | ||
AddRelayer(r, "r"). | ||
AddLink(ibctest.InterchainLink{ | ||
Chain1: gaia0, | ||
Chain2: gaia1, | ||
Relayer: r, | ||
}) | ||
|
||
rep := testreporter.NewNopReporter() | ||
eRep := rep.RelayerExecReporter(t) | ||
|
||
ctx := context.Background() | ||
require.NoError(t, ic.Build(ctx, eRep, ibctest.InterchainBuildOptions{ | ||
TestName: t.Name(), | ||
HomeDir: home, | ||
Pool: pool, | ||
NetworkID: network, | ||
})) | ||
|
||
testUser := ibctest.GetAndFundTestUsers(t, ctx, "gaia-user-1", 10_000_000, gaia0)[0] | ||
|
||
t.Run("broadcast success", func(t *testing.T) { | ||
b := cosmos.NewBroadcaster(t, gaia0.(*cosmos.CosmosChain)) | ||
transferAmount := types.Coin{Denom: gaia0.Config().Denom, Amount: types.NewInt(10000)} | ||
|
||
msg := transfertypes.NewMsgTransfer("transfer", "channel-0", transferAmount, testUser.Bech32Address(gaia0.Config().Bech32Prefix), testUser.Bech32Address(gaia1.Config().Bech32Prefix), clienttypes.NewHeight(1, 1000), 0) | ||
resp, err := broadcast.Tx(ctx, b, testUser, msg) | ||
require.NoError(t, err) | ||
require.NotNil(t, resp) | ||
require.NotEqual(t, 0, resp.GasUsed) | ||
require.NotEqual(t, 0, resp.GasWanted) | ||
require.Equal(t, uint32(0), resp.Code) | ||
require.NotEmpty(t, resp.Data) | ||
require.NotEmpty(t, resp.TxHash) | ||
require.NotEmpty(t, resp.Events) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can this test also have an assertion that the user on gaia1 has received |
||
}) | ||
} | ||
|
||
// An external package that imports ibctest may not provide a GitSha when they provide a BlockDatabaseFile. | ||
// The GitSha field is documented as optional, so this should succeed. | ||
func TestInterchain_OmitGitSHA(t *testing.T) { | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the types here make more sense in the root
ibctest
package.