forked from smartcontractkit/chainlink-cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain.go
299 lines (261 loc) · 8.27 KB
/
chain.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
package cosmos
import (
"context"
"crypto/rand"
"fmt"
"math/big"
"time"
"github.com/pelletier/go-toml/v2"
"github.com/pkg/errors"
"go.uber.org/multierr"
sdk "github.com/cosmos/cosmos-sdk/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/jmoiron/sqlx"
"github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/adapters"
"github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/client"
"github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/config"
"github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/db"
"github.com/smartcontractkit/chainlink-cosmos/pkg/cosmos/txm"
"github.com/smartcontractkit/chainlink-common/pkg/chains"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/loop"
"github.com/smartcontractkit/chainlink-common/pkg/services"
"github.com/smartcontractkit/chainlink-common/pkg/types"
)
// defaultRequestTimeout is the default Cosmos client timeout.
// Note that while the cosmos node is processing a heavy block,
// requests can be delayed significantly (https://github.com/tendermint/tendermint/issues/6899),
// however there's nothing we can do but wait until the block is processed.
// So we set a fairly high timeout here.
// TODO(BCI-979): Remove this, or make this configurable with the updated client.
const defaultRequestTimeout = 30 * time.Second
// Chain is a wrap for easy use in other places in the core node
type Chain = adapters.Chain
// ChainOpts holds options for configuring a Chain.
type ChainOpts struct {
Logger logger.Logger
DB *sqlx.DB
KeyStore loop.Keystore
}
func (o *ChainOpts) Validate() (err error) {
required := func(s string) error {
return fmt.Errorf("%s is required", s)
}
if o.Logger == nil {
err = multierr.Append(err, required("Logger'"))
}
if o.DB == nil {
err = multierr.Append(err, required("DB"))
}
if o.KeyStore == nil {
err = multierr.Append(err, required("KeyStore"))
}
return
}
func NewChain(cfg *config.TOMLConfig, opts ChainOpts) (adapters.Chain, error) {
if !cfg.IsEnabled() {
return nil, fmt.Errorf("cannot create new chain with ID %s, the chain is disabled", *cfg.ChainID)
}
c, err := newChain(*cfg.ChainID, cfg, opts.DB, opts.KeyStore, opts.Logger)
if err != nil {
return nil, err
}
return c, nil
}
var _ adapters.Chain = (*chain)(nil)
type chain struct {
services.StateMachine
id string
cfg *config.TOMLConfig
txm *txm.Txm
lggr logger.Logger
}
func newChain(id string, cfg *config.TOMLConfig, db *sqlx.DB, ks loop.Keystore, lggr logger.Logger) (*chain, error) {
lggr = logger.With(lggr, "cosmosChainID", id)
var ch = chain{
id: id,
cfg: cfg,
lggr: logger.Named(lggr, "Chain"),
}
tc := func() (client.ReaderWriter, error) {
return ch.getClient("")
}
gpe := client.NewMustGasPriceEstimator([]client.GasPricesEstimator{
client.NewClosureGasPriceEstimator(func() (map[string]sdk.DecCoin, error) {
return map[string]sdk.DecCoin{
cfg.GasToken(): sdk.NewDecCoinFromDec(cfg.GasToken(), cfg.FallbackGasPrice()),
}, nil
}),
}, lggr)
ch.txm = txm.NewTxm(db, tc, *gpe, ch.id, cfg, ks, lggr)
return &ch, nil
}
func (c *chain) Name() string {
return c.lggr.Name()
}
func (c *chain) ID() string {
return c.id
}
func (c *chain) ChainID() string {
return c.id
}
func (c *chain) Config() config.Config {
return c.cfg
}
func (c *chain) TxManager() adapters.TxManager {
return c.txm
}
func (c *chain) Reader(name string) (client.Reader, error) {
return c.getClient(name)
}
// getClient returns a client, optionally requiring a specific node by name.
func (c *chain) getClient(name string) (client.ReaderWriter, error) {
var node db.Node
if name == "" { // Any node
nodes, err := c.cfg.ListNodes()
if err != nil {
return nil, fmt.Errorf("failed to list nodes: %w", err)
}
if len(nodes) == 0 {
return nil, errors.New("no nodes available")
}
nodeIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(nodes))))
if err != nil {
return nil, fmt.Errorf("could not generate a random node index: %w", err)
}
node = nodes[nodeIndex.Int64()]
} else { // Named node
var err error
node, err = c.cfg.GetNode(name)
if err != nil {
return nil, fmt.Errorf("failed to get node named %s: %w", name, err)
}
if node.CosmosChainID != c.id {
return nil, fmt.Errorf("failed to create client for chain %s with node %s: wrong chain id %s", c.id, name, node.CosmosChainID)
}
}
client, err := client.NewClient(c.id, node.TendermintURL, defaultRequestTimeout, logger.Named(c.lggr, "Client."+name))
if err != nil {
return nil, fmt.Errorf("failed to create client: %w", err)
}
c.lggr.Debugw("Created client", "name", node.Name, "tendermint-url", node.TendermintURL)
return client, nil
}
// Start starts cosmos chain.
func (c *chain) Start(ctx context.Context) error {
return c.StartOnce("Chain", func() error {
c.lggr.Debug("Starting")
return c.txm.Start(ctx)
})
}
func (c *chain) Close() error {
return c.StopOnce("Chain", func() error {
c.lggr.Debug("Stopping")
return c.txm.Close()
})
}
func (c *chain) Ready() error {
return multierr.Combine(
c.StateMachine.Ready(),
c.txm.Ready(),
)
}
func (c *chain) HealthReport() map[string]error {
m := map[string]error{c.Name(): c.Healthy()}
services.CopyHealth(m, c.txm.HealthReport())
return m
}
// ChainService interface
func (c *chain) GetChainStatus(ctx context.Context) (types.ChainStatus, error) {
toml, err := c.cfg.TOMLString()
if err != nil {
return types.ChainStatus{}, err
}
return types.ChainStatus{
ID: c.id,
Enabled: *c.cfg.Enabled,
Config: toml,
}, nil
}
func (c *chain) ListNodeStatuses(ctx context.Context, pageSize int32, pageToken string) (stats []types.NodeStatus, nextPageToken string, total int, err error) {
return chains.ListNodeStatuses(int(pageSize), pageToken, c.listNodeStatuses)
}
func (c *chain) Transact(ctx context.Context, from, to string, amount *big.Int, balanceCheck bool) error {
fromAcc, err := sdk.AccAddressFromBech32(from)
if err != nil {
return fmt.Errorf("failed to parse from account: %s", fromAcc)
}
toAcc, err := sdk.AccAddressFromBech32(to)
if err != nil {
return fmt.Errorf("failed to parse from account: %s", toAcc)
}
coin := sdk.Coin{Amount: sdk.NewIntFromBigInt(amount), Denom: c.Config().GasToken()}
txm := c.TxManager()
if balanceCheck {
var reader client.Reader
reader, err = c.Reader("")
if err != nil {
return fmt.Errorf("chain unreachable: %v", err)
}
gasPrice, err2 := txm.GasPrice()
if err2 != nil {
return fmt.Errorf("gas price unavailable: %v", err2)
}
err = validateBalance(reader, gasPrice, fromAcc, coin)
if err != nil {
return fmt.Errorf("failed to validate balance: %v", err)
}
}
sendMsg := bank.NewMsgSend(fromAcc, toAcc, sdk.Coins{coin})
_, err = txm.Enqueue(ctx, "", sendMsg)
if err != nil {
return fmt.Errorf("failed to enqueue tx: %w", err)
}
return nil
}
// TODO BCF-2602 statuses are static for non-evm chain and should be dynamic
func (c *chain) listNodeStatuses(start, end int) ([]types.NodeStatus, int, error) {
stats := make([]types.NodeStatus, 0)
total := len(c.cfg.Nodes)
if start >= total {
return stats, total, chains.ErrOutOfRange
}
if end > total {
end = total
}
nodes := c.cfg.Nodes[start:end]
for _, node := range nodes {
stat, err := nodeStatus(node, c.ChainID())
if err != nil {
return stats, total, err
}
stats = append(stats, stat)
}
return stats, total, nil
}
func nodeStatus(n *config.Node, id string) (types.NodeStatus, error) {
var s types.NodeStatus
s.ChainID = id
s.Name = *n.Name
b, err := toml.Marshal(n)
if err != nil {
return types.NodeStatus{}, err
}
s.Config = string(b)
return s, nil
}
// maxGasUsedTransfer is an upper bound on how much gas we expect a MsgSend for a single coin to use.
const maxGasUsedTransfer = 100_000
// validateBalance validates that fromAddr's balance can cover coin, including fees at gasPrice.
func validateBalance(reader client.Reader, gasPrice sdk.DecCoin, fromAddr sdk.AccAddress, coin sdk.Coin) error {
balance, err := reader.Balance(fromAddr, coin.GetDenom())
if err != nil {
return err
}
fee := gasPrice.Amount.MulInt64(maxGasUsedTransfer).RoundInt()
need := coin.Amount.Add(fee)
if balance.Amount.LT(need) {
return errors.Errorf("balance %q is too low for this transaction to be executed: need %s total, including %s fee", balance, need, fee)
}
return nil
}