This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
client.go
244 lines (207 loc) · 6.83 KB
/
client.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
package rpc
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
// unnamed import of statik for swagger UI support
_ "github.com/bandprotocol/d3n/chain/client/lcd/statik"
"github.com/bandprotocol/d3n/chain/x/zoracle"
)
const (
requestIDTag = "requestID"
)
func getLatestBlocks(cliCtx context.CLIContext, page, limit int) ([]byte, error) {
node, err := cliCtx.GetNode()
if err != nil {
return nil, err
}
status, err := node.Status()
if err != nil {
return nil, err
}
blockHeight := status.SyncInfo.LatestBlockHeight
res := make([]*ctypes.ResultBlock, 0)
for i := (page - 1) * limit; i < page*limit && i < int(blockHeight); i++ {
height := blockHeight - int64(i)
block, err := node.Block(&height)
if err != nil {
return nil, err
}
res = append(res, block)
}
if cliCtx.Indent {
return codec.Cdc.MarshalJSONIndent(res, "", " ")
}
return codec.Cdc.MarshalJSON(res)
}
func LatestBlocksRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 10)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
if limit > 100 {
rest.WriteErrorResponse(w, http.StatusBadRequest, "limit must not be greater than 100.")
return
}
output, err := getLatestBlocks(cliCtx, page, limit)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponseBare(w, cliCtx, output)
}
}
func LatestTxsRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
_, page, limit, err := rest.ParseHTTPArgs(r)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
if limit > 100 {
rest.WriteErrorResponse(w, http.StatusBadRequest, "limit must not be greater than 100.")
return
}
// TODO: (1) Sort result in desc order after tendermint/tendermint:#4253 is released
// TODO: (2) Perform binary search on 'tx.height>?' to optimize the performance
// Temporary implementation to get latest tx sort by descending timestamp
// Pull request at bandprotocol/d3n:#224
node, _ := cliCtx.GetNode()
block, _ := node.Block(nil)
totalTxs := int(block.Block.Header.TotalTxs)
endIndex := totalTxs - (page-1)*limit
startIndex := totalTxs - page*limit + 1
var result sdk.SearchTxsResult
result.PageNumber = page
result.TotalCount = totalTxs
result.Limit = limit
result.PageTotal = (totalTxs-1)/limit + 1
result.Txs = make([]sdk.TxResponse, 0)
if startIndex < 1 {
startIndex = 1
}
if endIndex < 1 {
result.Count = 0
rest.PostProcessResponseBare(w, cliCtx, result)
return
}
todoIndex := startIndex
for todoIndex <= endIndex {
pageOfTodoIndex := (todoIndex-1)/limit + 1
startIndexOfPage := (pageOfTodoIndex-1)*limit + 1
searchResult, err := utils.QueryTxsByEvents(cliCtx, []string{"tx.height>0"}, pageOfTodoIndex, limit)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
for i, tx := range searchResult.Txs {
indexOfTx := startIndexOfPage + i
if indexOfTx >= startIndex && indexOfTx <= endIndex {
result.Txs = append(result.Txs, tx)
todoIndex = indexOfTx + 1
}
}
}
result.Count = len(result.Txs)
for i, j := 0, len(result.Txs)-1; i < j; i, j = i+1, j-1 {
result.Txs[i], result.Txs[j] = result.Txs[j], result.Txs[i]
}
rest.PostProcessResponseBare(w, cliCtx, result)
}
}
func GetHealthStatus(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
node, err := cliCtx.GetNode()
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
block, err := node.Block(nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
result := "UP"
if time.Now().Sub(block.Block.Header.Time) > 3*time.Minute {
result = "DOWN"
}
w.Write([]byte(result))
}
}
func GetProviderStatus(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
reqNumberResp, _, err := cliCtx.Query("custom/zoracle/request_number")
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
var requestID string
err = json.Unmarshal(reqNumberResp, &requestID)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
res, _, err := cliCtx.Query(fmt.Sprintf("custom/zoracle/request/%s", requestID))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
var request zoracle.RequestQuerierInfo
err = cliCtx.Codec.UnmarshalJSON(res, &request)
block, err := cliCtx.Client.Block(nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
numReporters := len(request.Reports)
status := "GOOD"
// TODO: Remove hard-coded provider count threshold
if block.Block.Height > request.Request.ExpirationHeight && numReporters < 3 {
fmt.Printf(`BAD ------- requestId: %s, reports: %d`, requestID, numReporters)
status = "BAD"
}
rest.PostProcessResponseBare(w, cliCtx, struct {
Height int64 `json:"height"`
RequestID string `json:"id"`
NumReporters int `json:"num_reporters"`
Status string `json:"status"`
}{
Height: block.Block.Height,
RequestID: requestID,
NumReporters: numReporters,
Status: status,
})
}
}
func ServeSwaggerUI() http.Handler {
statikFS, err := fs.New()
if err != nil {
panic(err)
}
staticServer := http.FileServer(statikFS)
return http.StripPrefix("/swagger-ui/", staticServer)
}
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc("/bandchain/blocks/latest", LatestBlocksRequestHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/bandchain/txs/latest", LatestTxsRequestHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/bandchain/evm-validators", GetEVMValidators(cliCtx)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/bandchain/proof/{%s}", requestIDTag), GetProofHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/bandchain/health_check", GetHealthStatus(cliCtx)).Methods("GET")
r.HandleFunc("/bandchain/provider_status", GetProviderStatus(cliCtx)).Methods("GET")
r.PathPrefix("/swagger-ui/").Handler(ServeSwaggerUI())
}