-
Notifications
You must be signed in to change notification settings - Fork 41
/
handler.go
269 lines (226 loc) · 7.69 KB
/
handler.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
package yoda
import (
"encoding/hex"
"strconv"
ckeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/bandprotocol/chain/hooks/common"
"github.com/bandprotocol/chain/x/oracle/types"
)
type processingResult struct {
rawReport types.RawReport
version string
err error
}
func handleTransaction(c *Context, l *Logger, tx tmtypes.TxResult) {
l.Debug(":eyes: Inspecting incoming transaction: %X", tmhash.Sum(tx.Tx))
if tx.Result.Code != 0 {
l.Debug(":alien: Skipping transaction with non-zero code: %d", tx.Result.Code)
return
}
logs, err := sdk.ParseABCILogs(tx.Result.Log)
if err != nil {
l.Error(":cold_sweat: Failed to parse transaction logs with error: %s", err.Error())
return
}
for _, log := range logs {
messageType, err := GetEventValue(log, sdk.EventTypeMessage, sdk.AttributeKeyAction)
if err != nil {
l.Error(":cold_sweat: Failed to get message action type with error: %s", err.Error())
continue
}
if messageType == (types.MsgRequestData{}).Type() {
go handleRequestLog(c, l, log)
} else {
l.Debug(":ghost: Skipping non-{request/packet} type: %s", messageType)
} /*else if messageType == (ibc.MsgPacket{}).Type() {
// Try to get request id from packet. If not then return error.
_, err := GetEventValue(log, types.EventTypeRequest, types.AttributeKeyID)
if err != nil {
l.Debug(":ghost: Skipping non-request packet")
return
}
go handleRequestLog(c, l, log)
} */
}
}
func handleRequestLog(c *Context, l *Logger, log sdk.ABCIMessageLog) {
idStr, err := GetEventValue(log, types.EventTypeRequest, types.AttributeKeyID)
if err != nil {
l.Error(":cold_sweat: Failed to parse request id with error: %s", err.Error())
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
l.Error(":cold_sweat: Failed to convert %s to integer with error: %s", idStr, err.Error())
return
}
l = l.With("rid", id)
// If id is in pending requests list, then skip it.
if c.pendingRequests[types.RequestID(id)] {
l.Debug(":eyes: Request is in pending list, then skip")
return
}
// Skip if not related to this validator
validators := GetEventValues(log, types.EventTypeRequest, types.AttributeKeyValidator)
hasMe := false
for _, validator := range validators {
if validator == c.validator.String() {
hasMe = true
break
}
}
if !hasMe {
l.Debug(":next_track_button: Skip request not related to this validator")
return
}
l.Info(":delivery_truck: Processing incoming request event")
reqs, err := GetRawRequests(log)
if err != nil {
l.Error(":skull: Failed to parse raw requests with error: %s", err.Error())
}
keyIndex := c.nextKeyIndex()
key := c.keys[keyIndex]
reports, execVersions := handleRawRequests(c, l, types.RequestID(id), reqs, key)
rawAskCount := GetEventValues(log, types.EventTypeRequest, types.AttributeKeyAskCount)
if len(rawAskCount) != 1 {
panic("Fail to get ask count")
}
askCount := common.Atoi(rawAskCount[0])
rawMinCount := GetEventValues(log, types.EventTypeRequest, types.AttributeKeyMinCount)
if len(rawMinCount) != 1 {
panic("Fail to get min count")
}
minCount := common.Atoi(rawMinCount[0])
rawCallData := GetEventValues(log, types.EventTypeRequest, types.AttributeKeyCalldata)
if len(rawCallData) != 1 {
panic("Fail to get call data")
}
callData, err := hex.DecodeString(rawCallData[0])
if err != nil {
l.Error(":skull: Fail to parse call data: %s", err.Error())
}
var clientID string
rawClientID := GetEventValues(log, types.EventTypeRequest, types.AttributeKeyClientID)
if len(rawClientID) > 0 {
clientID = rawClientID[0]
}
c.pendingMsgs <- ReportMsgWithKey{
msg: types.NewMsgReportData(types.RequestID(id), reports, c.validator, key.GetAddress()),
execVersion: execVersions,
keyIndex: keyIndex,
feeEstimationData: FeeEstimationData{
askCount: askCount,
minCount: minCount,
callData: callData,
rawRequests: reqs,
clientID: clientID,
},
}
}
func handlePendingRequest(c *Context, l *Logger, id types.RequestID) {
req, err := GetRequest(c, l, id)
if err != nil {
l.Error(":skull: Failed to get request with error: %s", err.Error())
return
}
l.Info(":delivery_truck: Processing pending request")
keyIndex := c.nextKeyIndex()
key := c.keys[keyIndex]
var rawRequests []rawRequest
// prepare raw requests
for _, raw := range req.RawRequests {
hash, err := GetDataSourceHash(c, l, raw.DataSourceID)
if err != nil {
l.Error(":skull: Failed to get data source hash with error: %s", err.Error())
return
}
rawRequests = append(rawRequests, rawRequest{
dataSourceID: raw.DataSourceID,
dataSourceHash: hash,
externalID: raw.ExternalID,
calldata: string(raw.Calldata),
})
}
// process raw requests
reports, execVersions := handleRawRequests(c, l, id, rawRequests, key)
c.pendingMsgs <- ReportMsgWithKey{
msg: types.NewMsgReportData(types.RequestID(id), reports, c.validator, key.GetAddress()),
execVersion: execVersions,
keyIndex: keyIndex,
feeEstimationData: FeeEstimationData{
askCount: int64(len(req.RequestedValidators)),
minCount: int64(req.MinCount),
callData: req.Calldata,
rawRequests: rawRequests,
clientID: req.ClientID,
},
}
}
func handleRawRequests(c *Context, l *Logger, id types.RequestID, reqs []rawRequest, key keys.Info) (reports []types.RawReport, execVersions []string) {
resultsChan := make(chan processingResult, len(reqs))
for _, req := range reqs {
go handleRawRequest(c, l.With("did", req.dataSourceID, "eid", req.externalID), req, key, types.RequestID(id), resultsChan)
}
versions := map[string]bool{}
for range reqs {
result := <-resultsChan
reports = append(reports, result.rawReport)
if result.err == nil {
versions[result.version] = true
}
}
for version := range versions {
execVersions = append(execVersions, version)
}
return
}
func handleRawRequest(c *Context, l *Logger, req rawRequest, key keys.Info, id types.RequestID, processingResultCh chan processingResult) {
exec, err := GetExecutable(c, l, req.dataSourceHash)
if err != nil {
l.Error(":skull: Failed to load data source with error: %s", err.Error())
processingResultCh <- processingResult{
rawReport: types.NewRawReport(
req.externalID, 255, []byte("FAIL_TO_LOAD_DATA_SOURCE"),
),
err: err,
}
return
}
vmsg := NewVerificationMessage(cfg.ChainID, c.validator, id, req.externalID)
sig, pubkey, err := keybase.Sign(key.GetName(), ckeys.DefaultKeyPass, vmsg.GetSignBytes())
if err != nil {
l.Error(":skull: Failed to sign verify message: %s", err.Error())
processingResultCh <- processingResult{
rawReport: types.NewRawReport(req.externalID, 255, nil),
err: err,
}
}
result, err := c.executor.Exec(exec, req.calldata, map[string]interface{}{
"BAND_CHAIN_ID": vmsg.ChainID,
"BAND_VALIDATOR": vmsg.Validator.String(),
"BAND_REQUEST_ID": strconv.Itoa(int(vmsg.RequestID)),
"BAND_EXTERNAL_ID": strconv.Itoa(int(vmsg.ExternalID)),
"BAND_REPORTER": sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pubkey),
"BAND_SIGNATURE": sig,
})
if err != nil {
l.Error(":skull: Failed to execute data source script: %s", err.Error())
processingResultCh <- processingResult{
rawReport: types.NewRawReport(req.externalID, 255, nil),
err: err,
}
} else {
l.Debug(
":sparkles: Query data done with calldata: %q, result: %q, exitCode: %d",
req.calldata, result.Output, result.Code,
)
processingResultCh <- processingResult{
rawReport: types.NewRawReport(req.externalID, result.Code, result.Output),
version: result.Version,
}
}
}