-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathbroadcaster.go
238 lines (204 loc) · 7.91 KB
/
broadcaster.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package cosmos
import (
"bytes"
"context"
"fmt"
"path"
"testing"
"time"
"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"
authTx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/strangelove-ventures/interchaintest/v7/internal/dockerutil"
"github.com/strangelove-ventures/interchaintest/v7/testutil"
)
type ClientContextOpt func(clientContext client.Context) client.Context
type FactoryOpt func(factory tx.Factory) tx.Factory
type User interface {
KeyName() string
FormattedAddress() string
}
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[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 []FactoryOpt
// clientContextOptions is a slice of broadcast.ClientContextOpt which enables arbitrary configuration of the client.Context.
clientContextOptions []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[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 ...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 ...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. ConfigureFactoryOptions can be used to specify arbitrary options to configure the returned
// factory.
func (b *Broadcaster) GetFactory(ctx context.Context, user User) (tx.Factory, error) {
clientContext, err := b.GetClientContext(ctx, user)
if err != nil {
return tx.Factory{}, err
}
sdkAdd, err := sdk.AccAddressFromBech32(user.FormattedAddress())
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. ConfigureClientContextOptions can be used to configure arbitrary options to configure the returned
// client.Context.
func (b *Broadcaster) GetClientContext(ctx context.Context, user User) (client.Context, error) {
chain := b.chain
cn := chain.getFullNode()
_, ok := b.keyrings[user]
if !ok {
localDir := b.t.TempDir()
containerKeyringDir := path.Join(cn.HomeDir(), "keyring-test")
kr, err := dockerutil.NewLocalKeyringFromDockerContainer(ctx, cn.DockerClient, localDir, containerKeyringDir, cn.containerLifecycle.ContainerID())
if err != nil {
return client.Context{}, err
}
b.keyrings[user] = kr
}
sdkAdd, err := sdk.AccAddressFromBech32(user.FormattedAddress())
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 User) ([]byte, error) {
if b.buf == nil || b.buf.Len() == 0 {
return nil, fmt.Errorf("empty buffer, transaction has not been 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 := b.chain.cfg.EncodingConfig.Codec.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 User, sdkAdd sdk.AccAddress) client.Context {
// initialize a clean buffer each time
b.buf.Reset()
kr := b.keyrings[fromUser]
cn := b.chain.getFullNode()
return cn.CliContext().
WithOutput(b.buf).
WithFrom(fromUser.FormattedAddress()).
WithFromAddress(sdkAdd).
WithFromName(fromUser.KeyName()).
WithSkipConfirmation(true).
WithAccountRetriever(authtypes.AccountRetriever{}).
WithKeyring(kr).
WithBroadcastMode(flags.BroadcastSync).
WithCodec(b.chain.cfg.EncodingConfig.Codec)
// NOTE: the returned context used to have .WithHomeDir(cn.Home),
// but that field no longer exists and the test against Broadcaster still passes without it.
}
// 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("interchaintest").
WithTxConfig(clientCtx.TxConfig).
WithAccountRetriever(clientCtx.AccountRetriever).
WithKeybase(clientCtx.Keyring).
WithChainID(clientCtx.ChainID).
WithSimulateAndExecute(false)
}
// BroadcastTx 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 BroadcastTx(ctx context.Context, broadcaster *Broadcaster, broadcastingUser User, msgs ...sdk.Msg) (sdk.TxResponse, error) {
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
}
err = testutil.WaitForCondition(time.Second*30, time.Second*5, func() (bool, error) {
var err error
txBytes, err = broadcaster.GetTxResponseBytes(ctx, broadcastingUser)
if err != nil {
return false, nil
}
return true, nil
})
if err != nil {
return sdk.TxResponse{}, err
}
respWithTxHash, err := broadcaster.UnmarshalTxResponseBytes(ctx, txBytes)
if err != nil {
return sdk.TxResponse{}, err
}
resp, err := authTx.QueryTx(cc, respWithTxHash.TxHash)
if err != nil {
// if we fail to query the tx, it means an error occurred with the original message broadcast.
// we should return this instead.
originalResp, err := broadcaster.UnmarshalTxResponseBytes(ctx, txBytes)
if err != nil {
return sdk.TxResponse{}, err
}
return originalResp, nil
}
return *resp, nil
}