forked from strangelove-ventures/interchaintest
/
hermes_relayer.go
351 lines (302 loc) · 12.1 KB
/
hermes_relayer.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package hermes
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"github.com/docker/docker/client"
"github.com/odin-protocol/interchaintest/v7/ibc"
"github.com/odin-protocol/interchaintest/v7/relayer"
"github.com/pelletier/go-toml"
"go.uber.org/zap"
)
const (
hermes = "hermes"
defaultContainerImage = "ghcr.io/informalsystems/hermes"
DefaultContainerVersion = "v1.7.1"
hermesDefaultUidGid = "1000:1000"
hermesHome = "/home/hermes"
hermesConfigPath = ".hermes/config.toml"
)
var (
_ ibc.Relayer = &Relayer{}
// parseRestoreKeyOutputPattern extracts the address from the hermes output.
// SUCCESS Restored key 'g2-2' (cosmos1czklnpzwaq3hfxtv6ne4vas2p9m5q3p3fgkz8e) on chain g2-2
parseRestoreKeyOutputPattern = regexp.MustCompile(`\((.*)\)`)
)
// Relayer is the ibc.Relayer implementation for hermes.
type Relayer struct {
*relayer.DockerRelayer
paths map[string]*pathConfiguration
chainConfigs []ChainConfig
}
// ChainConfig holds all values required to write an entry in the "chains" section in the hermes config file.
type ChainConfig struct {
cfg ibc.ChainConfig
keyName, rpcAddr, grpcAddr string
}
// pathConfiguration represents the concept of a "path" which is implemented at the interchain test level rather
// than the hermes level.
type pathConfiguration struct {
chainA, chainB pathChainConfig
}
// pathChainConfig holds all values that will be required when interacting with a path.
type pathChainConfig struct {
chainID string
clientID string
connectionID string
portID string
}
// NewHermesRelayer returns a new hermes relayer.
func NewHermesRelayer(log *zap.Logger, testName string, cli *client.Client, networkID string, options ...relayer.RelayerOpt) *Relayer {
c := commander{log: log}
options = append(options, relayer.HomeDir(hermesHome))
dr, err := relayer.NewDockerRelayer(context.TODO(), log, testName, cli, networkID, c, options...)
if err != nil {
panic(err)
}
c.extraStartFlags = dr.GetExtraStartupFlags()
return &Relayer{
DockerRelayer: dr,
}
}
// AddChainConfiguration is called once per chain configuration, which means that in the case of hermes, the single
// config file is overwritten with a new entry each time this function is called.
func (r *Relayer) AddChainConfiguration(ctx context.Context, rep ibc.RelayerExecReporter, chainConfig ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) error {
configContent, err := r.configContent(chainConfig, keyName, rpcAddr, grpcAddr)
if err != nil {
return fmt.Errorf("failed to generate config content: %w", err)
}
if err := r.WriteFileToHomeDir(ctx, hermesConfigPath, configContent); err != nil {
return fmt.Errorf("failed to write hermes config: %w", err)
}
return r.validateConfig(ctx, rep)
}
func (r *Relayer) MarkChainAsConsumer(ctx context.Context, chainID string) error {
bz, err := r.ReadFileFromHomeDir(ctx, hermesConfigPath)
if err != nil {
return err
}
var cfg Config
err = toml.Unmarshal(bz, &cfg)
if err != nil {
return err
}
for i, chain := range cfg.Chains {
if chain.ID == chainID {
chain.CCVConsumerChain = true
cfg.Chains[i] = chain
break
}
}
bz, err = toml.Marshal(cfg)
if err != nil {
return err
}
return r.WriteFileToHomeDir(ctx, hermesConfigPath, bz)
}
// LinkPath performs the operations that happen when a path is linked. This includes creating clients, creating connections
// and establishing a channel. This happens across multiple operations rather than a single link path cli command.
func (r *Relayer) LinkPath(ctx context.Context, rep ibc.RelayerExecReporter, pathName string, channelOpts ibc.CreateChannelOptions, clientOpts ibc.CreateClientOptions) error {
_, ok := r.paths[pathName]
if !ok {
return fmt.Errorf("path %s not found", pathName)
}
if err := r.CreateClients(ctx, rep, pathName, clientOpts); err != nil {
return err
}
if err := r.CreateConnections(ctx, rep, pathName); err != nil {
return err
}
if err := r.CreateChannel(ctx, rep, pathName, channelOpts); err != nil {
return err
}
return nil
}
func (r *Relayer) CreateChannel(ctx context.Context, rep ibc.RelayerExecReporter, pathName string, opts ibc.CreateChannelOptions) error {
pathConfig := r.paths[pathName]
cmd := []string{hermes, "--json", "create", "channel", "--order", opts.Order.String(), "--a-chain", pathConfig.chainA.chainID, "--a-port", opts.SourcePortName, "--b-port", opts.DestPortName, "--a-connection", pathConfig.chainA.connectionID}
if opts.Version != "" {
cmd = append(cmd, "--channel-version", opts.Version)
}
res := r.Exec(ctx, rep, cmd, nil)
if res.Err != nil {
return res.Err
}
pathConfig.chainA.portID = opts.SourcePortName
pathConfig.chainB.portID = opts.DestPortName
return nil
}
func (r *Relayer) CreateConnections(ctx context.Context, rep ibc.RelayerExecReporter, pathName string) error {
pathConfig := r.paths[pathName]
cmd := []string{hermes, "--json", "create", "connection", "--a-chain", pathConfig.chainA.chainID, "--a-client", pathConfig.chainA.clientID, "--b-client", pathConfig.chainB.clientID}
res := r.Exec(ctx, rep, cmd, nil)
if res.Err != nil {
return res.Err
}
chainAConnectionID, chainBConnectionID, err := GetConnectionIDsFromStdout(res.Stdout)
if err != nil {
return err
}
pathConfig.chainA.connectionID = chainAConnectionID
pathConfig.chainB.connectionID = chainBConnectionID
return res.Err
}
func (r *Relayer) UpdateClients(ctx context.Context, rep ibc.RelayerExecReporter, pathName string) error {
pathConfig, ok := r.paths[pathName]
if !ok {
return fmt.Errorf("path %s not found", pathName)
}
updateChainACmd := []string{hermes, "--json", "update", "client", "--host-chain", pathConfig.chainA.chainID, "--client", pathConfig.chainA.clientID}
res := r.Exec(ctx, rep, updateChainACmd, nil)
if res.Err != nil {
return res.Err
}
updateChainBCmd := []string{hermes, "--json", "update", "client", "--host-chain", pathConfig.chainB.chainID, "--client", pathConfig.chainB.clientID}
return r.Exec(ctx, rep, updateChainBCmd, nil).Err
}
// CreateClients creates clients on both chains.
// Note: in the go relayer this can be done with a single command using the path reference,
// however in Hermes this needs to be done as two separate commands.
func (r *Relayer) CreateClients(ctx context.Context, rep ibc.RelayerExecReporter, pathName string, opts ibc.CreateClientOptions) error {
pathConfig := r.paths[pathName]
chainACreateClientCmd := []string{hermes, "--json", "create", "client", "--host-chain", pathConfig.chainA.chainID, "--reference-chain", pathConfig.chainB.chainID}
if opts.TrustingPeriod != "0" {
chainACreateClientCmd = append(chainACreateClientCmd, "--trusting-period", opts.TrustingPeriod)
}
res := r.Exec(ctx, rep, chainACreateClientCmd, nil)
if res.Err != nil {
return res.Err
}
chainAClientId, err := GetClientIdFromStdout(res.Stdout)
if err != nil {
return err
}
pathConfig.chainA.clientID = chainAClientId
chainBCreateClientCmd := []string{hermes, "--json", "create", "client", "--host-chain", pathConfig.chainB.chainID, "--reference-chain", pathConfig.chainA.chainID}
if opts.TrustingPeriod != "0" {
chainBCreateClientCmd = append(chainBCreateClientCmd, "--trusting-period", opts.TrustingPeriod)
}
res = r.Exec(ctx, rep, chainBCreateClientCmd, nil)
if res.Err != nil {
return res.Err
}
chainBClientId, err := GetClientIdFromStdout(res.Stdout)
if err != nil {
return err
}
pathConfig.chainB.clientID = chainBClientId
return res.Err
}
// RestoreKey restores a key from a mnemonic. In hermes, you must provide a file containing the mnemonic. We need
// to copy the contents of the mnemonic into a file on disk and then reference the newly created file.
func (r *Relayer) RestoreKey(ctx context.Context, rep ibc.RelayerExecReporter, cfg ibc.ChainConfig, keyName, mnemonic string) error {
chainID := cfg.ChainID
relativeMnemonicFilePath := fmt.Sprintf("%s/mnemonic.txt", chainID)
if err := r.WriteFileToHomeDir(ctx, relativeMnemonicFilePath, []byte(mnemonic)); err != nil {
return fmt.Errorf("failed to write mnemonic file: %w", err)
}
cmd := []string{hermes, "keys", "add", "--chain", chainID, "--mnemonic-file", fmt.Sprintf("%s/%s", r.HomeDir(), relativeMnemonicFilePath), "--key-name", keyName}
// Restoring a key should be near-instantaneous, so add a 1-minute timeout
// to detect if Docker has hung.
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
res := r.Exec(ctx, rep, cmd, nil)
if res.Err != nil {
return res.Err
}
addrBytes := parseRestoreKeyOutput(string(res.Stdout))
r.AddWallet(chainID, NewWallet(chainID, addrBytes, mnemonic))
return nil
}
func (r *Relayer) Flush(ctx context.Context, rep ibc.RelayerExecReporter, pathName string, channelID string) error {
path := r.paths[pathName]
cmd := []string{hermes, "clear", "packets", "--chain", path.chainA.chainID, "--channel", channelID, "--port", path.chainA.portID}
res := r.Exec(ctx, rep, cmd, nil)
return res.Err
}
// GeneratePath establishes an in memory path representation. The concept does not exist in hermes, so it is handled
// at the interchain test level.
func (r *Relayer) GeneratePath(ctx context.Context, rep ibc.RelayerExecReporter, srcChainID, dstChainID, pathName string) error {
if r.paths == nil {
r.paths = map[string]*pathConfiguration{}
}
r.paths[pathName] = &pathConfiguration{
chainA: pathChainConfig{
chainID: srcChainID,
},
chainB: pathChainConfig{
chainID: dstChainID,
},
}
return nil
}
// configContent returns the contents of the hermes config file as a byte array. Note: as hermes expects a single file
// rather than multiple config files, we need to maintain a list of chain configs each time they are added to write the
// full correct file update calling Relayer.AddChainConfiguration.
func (r *Relayer) configContent(cfg ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) ([]byte, error) {
r.chainConfigs = append(r.chainConfigs, ChainConfig{
cfg: cfg,
keyName: keyName,
rpcAddr: rpcAddr,
grpcAddr: grpcAddr,
})
hermesConfig := NewConfig(r.chainConfigs...)
bz, err := toml.Marshal(hermesConfig)
if err != nil {
return nil, err
}
return bz, nil
}
// validateConfig validates the hermes config file. Any errors are propagated to the test.
func (r *Relayer) validateConfig(ctx context.Context, rep ibc.RelayerExecReporter) error {
cmd := []string{hermes, "--config", fmt.Sprintf("%s/%s", r.HomeDir(), hermesConfigPath), "config", "validate"}
res := r.Exec(ctx, rep, cmd, nil)
if res.Err != nil {
return res.Err
}
return nil
}
// extractJsonResult extracts the json result for the hermes query.
func extractJsonResult(stdout []byte) []byte {
stdoutLines := strings.Split(string(stdout), "\n")
var jsonOutput string
for _, line := range stdoutLines {
if strings.Contains(line, "result") {
jsonOutput = line
break
}
}
return []byte(jsonOutput)
}
// GetClientIdFromStdout extracts the client ID from stdout.
func GetClientIdFromStdout(stdout []byte) (string, error) {
var clientCreationResult ClientCreationResponse
if err := json.Unmarshal(extractJsonResult(stdout), &clientCreationResult); err != nil {
return "", err
}
return clientCreationResult.Result.CreateClient.ClientID, nil
}
// GetConnectionIDsFromStdout extracts the connectionIDs on both ends from the stdout.
func GetConnectionIDsFromStdout(stdout []byte) (string, string, error) {
var connectionResponse ConnectionResponse
if err := json.Unmarshal(extractJsonResult(stdout), &connectionResponse); err != nil {
return "", "", err
}
return connectionResponse.Result.ASide.ConnectionID, connectionResponse.Result.BSide.ConnectionID, nil
}
// GetChannelIDsFromStdout extracts the channelIDs on both ends from stdout.
func GetChannelIDsFromStdout(stdout []byte) (string, string, error) {
var channelResponse ChannelCreationResponse
if err := json.Unmarshal(extractJsonResult(stdout), &channelResponse); err != nil {
return "", "", err
}
return channelResponse.Result.ASide.ChannelID, channelResponse.Result.BSide.ChannelID, nil
}
// parseRestoreKeyOutput extracts the address from the hermes output.
func parseRestoreKeyOutput(stdout string) string {
fullMatchIdx, addressGroupIdx := 0, 1
return parseRestoreKeyOutputPattern.FindAllStringSubmatch(stdout, -1)[fullMatchIdx][addressGroupIdx]
}