forked from cosmos/relayer
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathprovider.go
416 lines (356 loc) · 13.5 KB
/
provider.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package cosmos
import (
"context"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"sync"
"time"
provtypes "github.com/cometbft/cometbft/light/provider"
prov "github.com/cometbft/cometbft/light/provider/http"
rpchttp "github.com/cometbft/cometbft/rpc/client/http"
libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/gogoproto/proto"
commitmenttypes "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types"
cwrapper "github.com/cosmos/relayer/v2/client"
"github.com/cosmos/relayer/v2/relayer/codecs/ethermint"
"github.com/cosmos/relayer/v2/relayer/processor"
"github.com/cosmos/relayer/v2/relayer/provider"
"github.com/strangelove-ventures/cometbft-client/client"
"go.uber.org/zap"
)
var (
_ provider.ChainProvider = &CosmosProvider{}
_ provider.KeyProvider = &CosmosProvider{}
_ provider.DymensionHubProvider = &CosmosProvider{}
_ provider.ProviderConfig = &CosmosProviderConfig{}
)
const (
cometEncodingThreshold = "v0.37.0-alpha"
cometBlockResultsThreshold = "v0.38.0-alpha"
)
type CosmosProviderConfig struct {
KeyDirectory string `json:"key-directory" yaml:"key-directory"`
Key string `json:"key" yaml:"key"`
ChainName string `json:"-" yaml:"-"`
ChainID string `json:"chain-id" yaml:"chain-id"`
HttpAddr string `json:"http-addr" yaml:"http-addr"` // added to support http queries to Dym Hub
DymRollapp bool `json:"is-dym-rollapp" yaml:"is-dym-rollapp"` // added to support custom trust levels, blocking for canon client
TrustPeriod time.Duration `json:"trust-period" yaml:"trust-period"` // added to specify exact trust
RPCAddr string `json:"rpc-addr" yaml:"rpc-addr"`
AccountPrefix string `json:"account-prefix" yaml:"account-prefix"`
KeyringBackend string `json:"keyring-backend" yaml:"keyring-backend"`
GasAdjustment float64 `json:"gas-adjustment" yaml:"gas-adjustment"`
GasPrices string `json:"gas-prices" yaml:"gas-prices"`
MinGasAmount uint64 `json:"min-gas-amount" yaml:"min-gas-amount"`
MaxGasAmount uint64 `json:"max-gas-amount" yaml:"max-gas-amount"`
Debug bool `json:"debug" yaml:"debug"`
Timeout string `json:"timeout" yaml:"timeout"`
BlockTimeout string `json:"block-timeout" yaml:"block-timeout"`
OutputFormat string `json:"output-format" yaml:"output-format"`
SignModeStr string `json:"sign-mode" yaml:"sign-mode"`
ExtraCodecs []string `json:"extra-codecs" yaml:"extra-codecs"`
Modules []module.AppModuleBasic `json:"-" yaml:"-"`
Slip44 *int `json:"coin-type" yaml:"coin-type"`
SigningAlgorithm string `json:"signing-algorithm" yaml:"signing-algorithm"`
Broadcast provider.BroadcastMode `json:"broadcast-mode" yaml:"broadcast-mode"`
MinLoopDuration time.Duration `json:"min-loop-duration" yaml:"min-loop-duration"`
ExtensionOptions []provider.ExtensionOption `json:"extension-options" yaml:"extension-options"`
// If FeeGrantConfiguration is set, TXs submitted by the ChainClient will be signed by the FeeGrantees in a round-robin fashion by default.
FeeGrants *FeeGrantConfiguration `json:"feegrants" yaml:"feegrants"`
}
// By default, TXs will be signed by the feegrantees 'ManagedGrantees' keys in a round robin fashion.
// Clients can use other signing keys by invoking 'tx.SendMsgsWith' and specifying the signing key.
type FeeGrantConfiguration struct {
GranteesWanted int `json:"num_grantees" yaml:"num_grantees"`
// Normally this is the default ChainClient key
GranterKeyOrAddr string `json:"granter" yaml:"granter"`
// Whether we control the granter private key (if not, someone else must authorize our feegrants)
IsExternalGranter bool `json:"external_granter" yaml:"external_granter"`
// List of keys (by name) that this FeeGranter manages
ManagedGrantees []string `json:"grantees" yaml:"grantees"`
// Last checked on chain (0 means grants never checked and may not exist)
BlockHeightVerified int64 `json:"block_last_verified" yaml:"block_last_verified"`
// Index of the last ManagedGrantee used as a TX signer
GranteeLastSignerIndex int
}
func (pc CosmosProviderConfig) Validate() error {
if _, err := time.ParseDuration(pc.Timeout); err != nil {
return fmt.Errorf("invalid Timeout: %w", err)
}
return nil
}
func (pc CosmosProviderConfig) GetHttpAddr() (string, error) {
if pc.HttpAddr == "" {
rpc := pc.RPCAddr
parts := strings.Split(rpc, ":")
if 2 <= len(parts) {
host := parts[len(parts)-2]
return fmt.Sprintf("http:%s:1318", host), nil
}
return "", errors.New("http addr not specified in cfg and cannot derive from rpc addr")
}
return pc.HttpAddr, nil
}
func (pc CosmosProviderConfig) BroadcastMode() provider.BroadcastMode {
return pc.Broadcast
}
// NewProvider validates the CosmosProviderConfig, instantiates a ChainClient and then instantiates a CosmosProvider
func (pc CosmosProviderConfig) NewProvider(log *zap.Logger, homepath string, debug bool, chainName string) (provider.ChainProvider, error) {
if err := pc.Validate(); err != nil {
return nil, err
}
pc.KeyDirectory = keysDir(homepath, pc.ChainID)
pc.ChainName = chainName
pc.Modules = append([]module.AppModuleBasic{}, ModuleBasics...)
if pc.Broadcast == "" {
pc.Broadcast = provider.BroadcastModeBatch
}
cp := &CosmosProvider{
log: log,
PCfg: pc,
KeyringOptions: []keyring.Option{ethermint.EthSecp256k1Option()},
Input: os.Stdin,
Output: os.Stdout,
walletStateMap: map[string]*WalletState{},
// TODO: this is a bit of a hack, we should probably have a better way to inject modules
Cdc: MakeCodec(pc.Modules, pc.ExtraCodecs, pc.AccountPrefix, pc.AccountPrefix+"valoper"),
}
return cp, nil
}
type CosmosProvider struct {
log *zap.Logger
PCfg CosmosProviderConfig
Keybase keyring.Keyring
KeyringOptions []keyring.Option
RPCClient cwrapper.RPCClient
LightProvider provtypes.Provider
Input io.Reader
Output io.Writer
Cdc Codec
// TODO: GRPC Client type?
// nextAccountSeq uint64
feegrantMu sync.Mutex
// the map key is the TX signer, which can either be 'default' (provider key) or a feegrantee
// the purpose of the map is to lock on the signer from TX creation through submission,
// thus making TX sequencing errors less likely.
walletStateMap map[string]*WalletState
// metrics to monitor the provider
TotalFees sdk.Coins
totalFeesMu sync.Mutex
metrics *processor.PrometheusMetrics
// for comet < v0.37, decode tm events as base64
cometLegacyEncoding bool
// for comet < v0.38, use legacy RPC client for ResultsBlockResults
cometLegacyBlockResults bool
}
func (cc *CosmosProvider) IsDymensionRollapp() bool {
return cc.PCfg.DymRollapp
}
type WalletState struct {
NextAccountSequence uint64
Mu sync.Mutex
}
func (cc *CosmosProvider) ProviderConfig() provider.ProviderConfig {
return cc.PCfg
}
func (cc *CosmosProvider) ChainId() string {
return cc.PCfg.ChainID
}
func (cc *CosmosProvider) ChainName() string {
return cc.PCfg.ChainName
}
func (cc *CosmosProvider) Type() string {
return "cosmos"
}
func (cc *CosmosProvider) Key() string {
return cc.PCfg.Key
}
func (cc *CosmosProvider) Timeout() string {
return cc.PCfg.Timeout
}
// CommitmentPrefix returns the commitment prefix for Cosmos
func (cc *CosmosProvider) CommitmentPrefix() commitmenttypes.MerklePrefix {
return defaultChainPrefix
}
// Address returns the chains configured address as a string
func (cc *CosmosProvider) Address() (string, error) {
info, err := cc.Keybase.Key(cc.PCfg.Key)
if err != nil {
return "", err
}
acc, err := info.GetAddress()
if err != nil {
return "", err
}
out, err := cc.EncodeBech32AccAddr(acc)
if err != nil {
return "", err
}
return out, err
}
func (cc *CosmosProvider) MustEncodeAccAddr(addr sdk.AccAddress) string {
enc, err := cc.EncodeBech32AccAddr(addr)
if err != nil {
panic(err)
}
return enc
}
// AccountFromKeyOrAddress returns an account from either a key or an address.
// If 'keyOrAddress' is the empty string, this returns the default key's address.
func (cc *CosmosProvider) AccountFromKeyOrAddress(keyOrAddress string) (out sdk.AccAddress, err error) {
switch {
case keyOrAddress == "":
out, err = cc.GetKeyAddress(cc.PCfg.Key)
case cc.KeyExists(keyOrAddress):
out, err = cc.GetKeyAddress(keyOrAddress)
default:
out, err = sdk.GetFromBech32(keyOrAddress, cc.PCfg.AccountPrefix)
}
return
}
func (cc *CosmosProvider) TrustingPeriod(ctx context.Context, overrideUnbondingPeriod time.Duration, percentage int64) (time.Duration, error) {
if val := cc.PCfg.TrustPeriod; val != 0 { // legacy way of setting trust period for rollapp
cc.log.Info("Using trust period from config.", zap.Any("chain", cc.ChainId()), zap.Any("trust", val))
return cc.PCfg.TrustPeriod, nil
}
unbondingTime := overrideUnbondingPeriod
var err error
if unbondingTime == 0 {
unbondingTime, err = cc.QueryUnbondingPeriod(ctx)
if err != nil {
return 0, err
}
}
if cc.PCfg.DymRollapp {
temp := unbondingTime / 100 * 65 // hardcoded 0.65 multiplier TODO: https://github.com/dymensionxyz/dymension/issues/1209
return temp.Truncate(time.Second), nil
}
// We want the trusting period to be `percentage` of the unbonding time.
// Go mentions that the time.Duration type can track approximately 290 years.
// We don't want to lose precision if the duration is a very long duration
// by converting int64 to float64.
// Use integer math the whole time, first reducing by a factor of 100
// and then re-growing by the `percentage` param.
tp := time.Duration(int64(unbondingTime) / 100 * percentage)
// And we only want the trusting period to be whole hours.
// But avoid rounding if the time is less than 1 hour
// (otherwise the trusting period will go to 0)
if tp > time.Hour {
tp = tp.Truncate(time.Hour)
}
return tp, nil
}
// Sprint returns the json representation of the specified proto message.
func (cc *CosmosProvider) Sprint(toPrint proto.Message) (string, error) {
out, err := cc.Cdc.Marshaler.MarshalJSON(toPrint)
if err != nil {
return "", err
}
return string(out), nil
}
// SetPCAddr sets the rpc-addr for the chain.
// It will fail if the rpcAddr is invalid(not a url).
func (cc *CosmosProvider) SetRpcAddr(rpcAddr string) error {
cc.PCfg.RPCAddr = rpcAddr
return nil
}
// Init initializes the keystore, RPC client, amd light client provider.
// Once initialization is complete an attempt to query the underlying node's tendermint version is performed.
// NOTE: Init must be called after creating a new instance of CosmosProvider.
func (cc *CosmosProvider) Init(ctx context.Context) error {
keybase, err := keyring.New(
cc.PCfg.ChainID,
cc.PCfg.KeyringBackend,
cc.PCfg.KeyDirectory,
cc.Input,
cc.Cdc.Marshaler,
cc.KeyringOptions...,
)
if err != nil {
return err
}
// TODO: figure out how to deal with input or maybe just make all keyring backends test?
timeout, err := time.ParseDuration(cc.PCfg.Timeout)
if err != nil {
return err
}
c, err := client.NewClient(cc.PCfg.RPCAddr, timeout)
if err != nil {
return err
}
lightprovider, err := prov.New(cc.PCfg.ChainID, cc.PCfg.RPCAddr)
if err != nil {
return err
}
rpcClient := cwrapper.NewRPCClient(c)
cc.RPCClient = rpcClient
cc.LightProvider = lightprovider
cc.Keybase = keybase
return nil
}
// WaitForNBlocks blocks until the next block on a given chain
func (cc *CosmosProvider) WaitForNBlocks(ctx context.Context, n int64) error {
var initial int64
h, err := cc.RPCClient.Status(ctx)
if err != nil {
return err
}
if h.SyncInfo.CatchingUp {
return fmt.Errorf("chain catching up")
}
initial = h.SyncInfo.LatestBlockHeight
for {
h, err = cc.RPCClient.Status(ctx)
if err != nil {
return err
}
if h.SyncInfo.LatestBlockHeight > initial+n {
return nil
}
select {
case <-time.After(10 * time.Millisecond):
// Nothing to do.
case <-ctx.Done():
return ctx.Err()
}
}
}
func (cc *CosmosProvider) BlockTime(ctx context.Context, height int64) (time.Time, error) {
resultBlock, err := cc.RPCClient.Block(ctx, &height)
if err != nil {
return time.Time{}, err
}
return resultBlock.Block.Time, nil
}
func (cc *CosmosProvider) SetMetrics(m *processor.PrometheusMetrics) {
cc.metrics = m
}
func (cc *CosmosProvider) updateNextAccountSequence(sequenceGuard *WalletState, seq uint64) {
if seq > sequenceGuard.NextAccountSequence {
sequenceGuard.NextAccountSequence = seq
}
}
// keysDir returns a string representing the path on the local filesystem where the keystore will be initialized.
func keysDir(home, chainID string) string {
return path.Join(home, "keys", chainID)
}
// NewRPCClient initializes a new tendermint RPC client connected to the specified address.
func NewRPCClient(addr string, timeout time.Duration) (*rpchttp.HTTP, error) {
httpClient, err := libclient.DefaultHTTPClient(addr)
if err != nil {
return nil, err
}
httpClient.Timeout = timeout
rpcClient, err := rpchttp.NewWithClient(addr, "/websocket", httpClient)
if err != nil {
return nil, err
}
return rpcClient, nil
}