/
execute.go
265 lines (237 loc) · 8.38 KB
/
execute.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
package yoda
import (
"context"
"fmt"
"strings"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/version"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/authz"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
band "github.com/bandprotocol/chain/v2/app"
"github.com/bandprotocol/chain/v2/x/oracle/types"
)
var (
// Proto codec for encoding/decoding proto message
cdc = band.MakeEncodingConfig().Marshaler
)
func signAndBroadcast(
c *Context, key keyring.Info, msgs []sdk.Msg, gasLimit uint64, memo string,
) (string, error) {
clientCtx := client.Context{
Client: c.client,
TxConfig: band.MakeEncodingConfig().TxConfig,
BroadcastMode: "sync",
InterfaceRegistry: band.MakeEncodingConfig().InterfaceRegistry,
}
acc, err := queryAccount(clientCtx, key)
if err != nil {
return "", fmt.Errorf("unable to get account: %w", err)
}
txf := tx.Factory{}.
WithAccountNumber(acc.GetAccountNumber()).
WithSequence(acc.GetSequence()).
WithTxConfig(band.MakeEncodingConfig().TxConfig).
WithGas(gasLimit).WithGasAdjustment(1).
WithChainID(cfg.ChainID).
WithMemo(memo).
WithGasPrices(c.gasPrices).
WithKeybase(kb).
WithAccountRetriever(clientCtx.AccountRetriever)
execMsg := authz.NewMsgExec(key.GetAddress(), msgs)
txb, err := tx.BuildUnsignedTx(txf, &execMsg)
if err != nil {
return "", err
}
err = tx.Sign(txf, key.GetName(), txb, true)
if err != nil {
return "", err
}
txBytes, err := clientCtx.TxConfig.TxEncoder()(txb.GetTx())
if err != nil {
return "", err
}
// broadcast to a Tendermint node
res, err := clientCtx.BroadcastTx(txBytes)
if err != nil {
return "", err
}
// out, err := txBldr.WithKeybase(keybase).BuildAndSign(key.GetName(), ckeys.DefaultKeyPass, msgs)
// if err != nil {
// return "", fmt.Errorf("Failed to build tx with error: %s", err.Error())
// }
return res.TxHash, nil
}
func queryAccount(clientCtx client.Context, key keyring.Info) (client.Account, error) {
accountRetriever := authtypes.AccountRetriever{}
acc, err := accountRetriever.GetAccount(clientCtx, key.GetAddress())
if err != nil {
return nil, err
}
return acc, nil
}
func SubmitReport(c *Context, l *Logger, keyIndex int64, reports []ReportMsgWithKey) {
// Return key and update pending metric when done with SubmitReport whether successfully or not.
defer func() {
c.freeKeys <- keyIndex
}()
defer c.updatePendingGauge(int64(-len(reports)))
// Summarize execute version
versionMap := make(map[string]bool)
msgs := make([]sdk.Msg, len(reports))
ids := make([]types.RequestID, len(reports))
feeEstimations := make([]FeeEstimationData, len(reports))
for i, report := range reports {
if err := report.msg.ValidateBasic(); err != nil {
l.Error(":exploding_head: Failed to validate basic with error: %s", c, err.Error())
return
}
msgs[i] = report.msg
ids[i] = report.msg.RequestID
feeEstimations[i] = report.feeEstimationData
for _, exec := range report.execVersion {
versionMap[exec] = true
}
}
l = l.With("rids", ids)
versions := make([]string, 0, len(versionMap))
for exec := range versionMap {
versions = append(versions, exec)
}
memo := fmt.Sprintf("yoda:%s/exec:%s", version.Version, strings.Join(versions, ","))
key := c.keys[keyIndex]
// cliCtx := sdkCtx.CLIContext{Client: c.client, TrustNode: true, Codec: cdc}
clientCtx := client.Context{
Client: c.client,
TxConfig: band.MakeEncodingConfig().TxConfig,
InterfaceRegistry: band.MakeEncodingConfig().InterfaceRegistry,
}
gasLimit := estimateGas(c, l, msgs, feeEstimations)
// We want to resend transaction only if tx returns Out of gas error.
for sendAttempt := uint64(1); sendAttempt <= c.maxTry; sendAttempt++ {
var txHash string
l.Info(":e-mail: Sending report transaction attempt: (%d/%d)", sendAttempt, c.maxTry)
for broadcastTry := uint64(1); broadcastTry <= c.maxTry; broadcastTry++ {
l.Info(":writing_hand: Try to sign and broadcast report transaction(%d/%d)", broadcastTry, c.maxTry)
hash, err := signAndBroadcast(c, key, msgs, gasLimit, memo)
if err != nil {
// Use info level because this error can happen and retry process can solve this error.
l.Info(":warning: %s", err.Error())
time.Sleep(c.rpcPollInterval)
continue
}
// Transaction passed CheckTx process and wait to include in block.
txHash = hash
break
}
if txHash == "" {
l.Error(":exploding_head: Cannot try to broadcast more than %d try", c, c.maxTry)
return
}
txFound := false
FindTx:
for start := time.Now(); time.Since(start) < c.broadcastTimeout; {
time.Sleep(c.rpcPollInterval)
txRes, err := authtx.QueryTx(clientCtx, txHash)
if err != nil {
l.Debug(":warning: Failed to query tx with error: %s", err.Error())
continue
}
if txRes.Code == 0 {
l.Info(":smiling_face_with_sunglasses: Successfully broadcast tx with hash: %s", txHash)
c.updateSubmittedCount(int64(len(reports)))
return
}
if txRes.Codespace == sdkerrors.RootCodespace &&
txRes.Code == sdkerrors.ErrOutOfGas.ABCICode() {
// Increase gas limit and try to broadcast again
gasLimit = gasLimit * 110 / 100
l.Info(":fuel_pump: Tx(%s) is out of gas and will be rebroadcasted with %d gas", txHash, gasLimit)
txFound = true
break FindTx
} else {
l.Error(":exploding_head: Tx returned nonzero code %d with log %s, tx hash: %s", c, txRes.Code, txRes.RawLog, txRes.TxHash)
return
}
}
if !txFound {
l.Error(
":question_mark: Cannot get transaction response from hash: %s transaction might be included in the next few blocks or check your node's health.",
c,
txHash,
)
return
}
}
l.Error(":anxious_face_with_sweat: Cannot send reports with adjusted gas: %d", c, gasLimit)
}
// GetExecutable fetches data source executable using the provided client.
func GetExecutable(c *Context, l *Logger, hash string) ([]byte, error) {
resValue, err := c.fileCache.GetFile(hash)
if err != nil {
l.Debug(":magnifying_glass_tilted_left: Fetching data source hash: %s from bandchain querier", hash)
bz := cdc.MustMarshal(&types.QueryDataRequest{
DataHash: hash,
})
res, err := abciQuery(c, l, "/oracle.v1.Query/Data", bz)
if err != nil {
l.Error(":exploding_head: Failed to get data source with error: %s", c, err.Error())
return nil, err
}
var dr types.QueryDataResponse
err = cdc.Unmarshal(res.Response.GetValue(), &dr)
if err != nil {
l.Error(":exploding_head: Failed to unmarshal data source with error: %s", c, err.Error())
return nil, err
}
resValue = dr.Data
c.fileCache.AddFile(resValue)
} else {
l.Debug(":card_file_box: Found data source hash: %s in cache file", hash)
}
l.Debug(":balloon: Received data source hash: %s content: %q", hash, resValue[:32])
return resValue, nil
}
// GetDataSourceHash fetches data source hash by id
func GetDataSourceHash(c *Context, l *Logger, id types.DataSourceID) (string, error) {
res, err := abciQuery(c, l, fmt.Sprintf("/store/%s/key", types.StoreKey), types.DataSourceStoreKey(id))
if err != nil {
l.Error(":skull: Failed to get data source with error: %s", c, err.Error())
return "", err
}
var d types.DataSource
cdc.MustUnmarshal(res.Response.Value, &d)
return d.Filename, nil
}
// GetRequest fetches request by id
func GetRequest(c *Context, l *Logger, id types.RequestID) (types.Request, error) {
res, err := abciQuery(c, l, fmt.Sprintf("/store/%s/key", types.StoreKey), types.RequestStoreKey(id))
if err != nil {
l.Error(":skull: Failed to get request with error: %s", c, err.Error())
return types.Request{}, err
}
var r types.Request
cdc.MustUnmarshal(res.Response.Value, &r)
return r, nil
}
// abciQuery will try to query data from BandChain node maxTry time before give up and return error
func abciQuery(c *Context, l *Logger, path string, data []byte) (*ctypes.ResultABCIQuery, error) {
var lastErr error
for try := 0; try < int(c.maxTry); try++ {
res, err := c.client.ABCIQuery(context.Background(), path, data)
if err != nil {
l.Debug(":skull: Failed to query on %s request with error: %s", path, err.Error())
lastErr = err
time.Sleep(c.rpcPollInterval)
continue
}
return res, nil
}
return nil, lastErr
}