-
Notifications
You must be signed in to change notification settings - Fork 0
/
execute.go
197 lines (180 loc) · 6.61 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
package yoda
import (
"fmt"
"strings"
"time"
sdkCtx "github.com/cosmos/cosmos-sdk/client/context"
ckeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
"github.com/bandprotocol/bandchain-node/app"
"github.com/bandprotocol/bandchain-node/x/oracle/types"
rpcclient "github.com/tendermint/tendermint/rpc/client"
)
var (
cdc = app.MakeCodec()
)
// TODO: Improve precision of equation.
// const (
// rawReportMultiplier = uint64(10)
// dataSizeMultiplier = uint64(10)
// msgReportDataConstant = uint64(10)
// txSizeConstant = uint64(10)
// baseTransaction = uint64(30000)
// )
// Constant used to estimate gas price of reports transaction.
const (
dataSizeMultiplier = uint64(50)
msgReportDataConstant = uint64(16000)
txSizeConstant = uint64(5) // Using DefaultTxSizeCostPerByte of BandChain
baseTransaction = uint64(40000)
pendingRequests = uint64(4000)
)
func estimatedReportsGas(msgs []sdk.Msg) uint64 {
est := baseTransaction
txSize := uint64(0)
for _, msg := range msgs {
msg, ok := msg.(types.MsgReportData)
if !ok {
panic("Don't support non-report data message")
}
calldataSize := uint64(0)
for _, c := range msg.RawReports {
calldataSize += uint64(len(c.Data))
}
est += dataSizeMultiplier*calldataSize + msgReportDataConstant
txSize += uint64(len(msg.GetSignBytes()))
}
return est + txSize*txSizeConstant + pendingRequests
}
func signAndBroadcast(
c *Context, key keys.Info, msgs []sdk.Msg, gasLimit uint64, memo string,
) (string, error) {
cliCtx := sdkCtx.CLIContext{Client: c.client, TrustNode: true, Codec: cdc}
acc, err := auth.NewAccountRetriever(cliCtx).GetAccount(key.GetAddress())
if err != nil {
return "", fmt.Errorf("Failed to retreive account with error: %s", err.Error())
}
txBldr := auth.NewTxBuilder(
auth.DefaultTxEncoder(cdc), acc.GetAccountNumber(), acc.GetSequence(),
gasLimit, 1, false, cfg.ChainID, memo, sdk.NewCoins(), c.gasPrices,
)
// txBldr, err = authclient.EnrichWithGas(txBldr, cliCtx, []sdk.Msg{msg})
// if err != nil {
// l.Error(":exploding_head: Failed to enrich with gas with error: %s", err.Error())
// return
// }
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())
}
res, err := cliCtx.BroadcastTxSync(out)
if err != nil {
return "", fmt.Errorf("Failed to broadcast tx with error: %s", err.Error())
}
return res.TxHash, nil
}
func SubmitReport(c *Context, l *Logger, keyIndex int64, reports []ReportMsgWithKey) {
// Return key when done with SubmitReport whether successfully or not.
defer func() {
c.freeKeys <- keyIndex
}()
// Summarize execute version
versionMap := make(map[string]bool)
msgs := make([]sdk.Msg, len(reports))
ids := make([]types.RequestID, 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", err.Error())
return
}
msgs[i] = report.msg
ids[i] = report.msg.RequestID
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}
gasLimit := estimatedReportsGas(msgs)
// 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.maxTry)
return
}
txFound := false
FindTx:
for start := time.Now(); time.Since(start) < c.broadcastTimeout; {
time.Sleep(c.rpcPollInterval)
txRes, err := utils.QueryTx(cliCtx, txHash)
if err != nil {
l.Debug(":warning: Failed to query tx with error: %s", err.Error())
continue
}
switch txRes.Code {
case 0:
l.Info(":smiling_face_with_sunglasses: Successfully broadcast tx with hash: %s", txHash)
return
case 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
default:
l.Error(":exploding_head: Tx returned nonzero code %d with log %s, tx hash: %s", 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.", txHash)
return
}
}
l.Error(":anxious_face_with_sweat: Cannot send reports with adjusted gas: %d", gasLimit)
return
}
// 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)
res, err := c.client.ABCIQueryWithOptions(fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QueryData, hash), nil, rpcclient.ABCIQueryOptions{})
if err != nil {
l.Error(":exploding_head: Failed to get data source with error: %s", err.Error())
return nil, err
}
resValue = res.Response.GetValue()
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
}