-
Notifications
You must be signed in to change notification settings - Fork 128
/
apimiddleware.go
406 lines (369 loc) · 12.4 KB
/
apimiddleware.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package insight
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"github.com/decred/dcrd/chaincfg/chainhash"
apitypes "github.com/decred/dcrdata/v3/api/types"
m "github.com/decred/dcrdata/v3/middleware"
"github.com/go-chi/chi"
)
type contextKey int
const (
ctxRawHexTx contextKey = iota
ctxFrom
ctxTo
ctxNoAsm
ctxNoScriptSig
ctxNoSpent
ctxBlockHash
ctxBlockIndex
ctxNoTxList
ctxAddrCmd
ctxNbBlocks
)
// BlockHashPathAndIndexCtx is a middleware that embeds the value at the url
// part {blockhash}, and the corresponding block index, into a request context.
func (c *insightApiContext) BlockHashPathAndIndexCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := m.BlockHashPathAndIndexCtx(r, c.BlockData.ChainDB)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// StatusCtx is a middleware that embeds into the request context the data for
// the "?q=x" URL query, where x is "getInfo" or "getDifficulty" or
// "getBestBlockHash" or "getLastBlockHash".
func (c *insightApiContext) StatusInfoCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := m.StatusInfoCtx(r, c.BlockData.ChainDB)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (c *insightApiContext) getBlockHashCtx(r *http.Request) string {
hash := m.GetBlockHashCtx(r)
if hash == "" {
var err error
hash, err = c.BlockData.ChainDB.GetBlockHash(int64(m.GetBlockIndexCtx(r)))
if err != nil {
apiLog.Errorf("Unable to GetBlockHash: %v", err)
}
}
return hash
}
// GetRawHexTx retrieves the ctxRawHexTx data from the request context. If not
// set, the return value is an empty string.
func (c *insightApiContext) GetRawHexTx(r *http.Request) (string, bool) {
rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string)
if !ok {
apiLog.Trace("Rawtx hex transaction not set")
return "", false
}
return rawHexTx, true
}
// Process params given in post body for an broadcast tx endpoint.
func (c *insightApiContext) PostBroadcastTxCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req apitypes.InsightRawTx
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeInsightError(w, fmt.Sprintf("Error reading JSON message: %v", err))
return
}
err = json.Unmarshal(body, &req)
if err != nil {
writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err))
return
}
// Successful extraction of Body JSON as long as the rawtx is not empty
// string we should return it
if req.Rawtx == "" {
writeInsightError(w, fmt.Sprintf("rawtx cannot be an empty string."))
return
}
ctx := context.WithValue(r.Context(), ctxRawHexTx, req.Rawtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetToCtx retrieves the ctxTo data ("to") from the request context. If not
// set, the return value ok is false.
func (c *insightApiContext) GetToCtx(r *http.Request) (int64, bool) {
to, ok := r.Context().Value(ctxTo).(int)
if !ok {
return int64(0), false
}
return int64(to), true
}
// GetFromCtx retrieves the ctxFrom data ("from") from the request context.
// If not set, the return value is 0
func (c *insightApiContext) GetFromCtx(r *http.Request) int64 {
from, ok := r.Context().Value(ctxFrom).(int)
if !ok {
return int64(0)
}
return int64(from)
}
// GetNoAsmCtx retrieves the ctxNoAsm data ("noAsm") from the request context.
// If not set, the return value is false.
func (c *insightApiContext) GetNoAsmCtx(r *http.Request) bool {
noAsm, ok := r.Context().Value(ctxNoAsm).(bool)
if !ok {
return false
}
return noAsm
}
// GetNoScriptSigCtx retrieves the ctxNoScriptSig data ("noScriptSig") from the
// request context. If not set, the return value is false.
func (c *insightApiContext) GetNoScriptSigCtx(r *http.Request) bool {
noScriptSig, ok := r.Context().Value(ctxNoScriptSig).(bool)
if !ok {
return false
}
return noScriptSig
}
// GetNoSpentCtx retrieves the ctxNoSpent data ("noSpent") from the
// request context. If not set, the return value is false.
func (c *insightApiContext) GetNoSpentCtx(r *http.Request) bool {
noSpent, ok := r.Context().Value(ctxNoSpent).(bool)
if !ok {
return false
}
return noSpent
}
// FromToPaginationCtx will parse the query parameters for from/to values.
func (c *insightApiContext) FromToPaginationCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
to, from := r.FormValue("to"), r.FormValue("from")
fromint, err := strconv.Atoi(from)
if err == nil {
ctx = context.WithValue(r.Context(), ctxFrom, fromint)
}
toint, err := strconv.Atoi(to)
if err == nil {
ctx = context.WithValue(ctx, ctxTo, toint)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// ValidatePostCtx will confirm Post content length is valid.
func (c *insightApiContext) ValidatePostCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentLengthString := r.Header.Get("Content-Length")
contentLength, err := strconv.Atoi(contentLengthString)
if err != nil {
writeInsightError(w, "Content-Length Header must be set")
return
}
// Broadcast Tx has the largest possible body. Cap max content length
// to c.params.MaxTxSize * 2 plus some arbitrary extra for JSON
// encapsulation.
maxPayload := (c.params.MaxTxSize * 2) + 50
if contentLength > maxPayload {
writeInsightError(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload))
return
}
next.ServeHTTP(w, r)
})
}
// Process params given in post body for an addrs endpoint
func (c *insightApiContext) PostAddrsTxsCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req apitypes.InsightMultiAddrsTx
var from, to, noAsm, noScriptSig, noSpent int64
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err))
return
}
err = json.Unmarshal(body, &req)
if err != nil {
writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err))
return
}
// Successful extraction of Body JSON
ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addresses)
if req.From != "" {
from, err = req.From.Int64()
if err == nil {
ctx = context.WithValue(ctx, ctxFrom, int(from))
}
}
if req.To != "" {
to, err = req.To.Int64()
if err == nil {
ctx = context.WithValue(ctx, ctxTo, int(to))
}
}
if req.NoAsm != "" {
noAsm, err = req.NoAsm.Int64()
if err == nil && noAsm != 0 {
ctx = context.WithValue(ctx, ctxNoAsm, true)
}
}
if req.NoScriptSig != "" {
noScriptSig, err = req.NoScriptSig.Int64()
if err == nil && noScriptSig != 0 {
ctx = context.WithValue(ctx, ctxNoScriptSig, true)
}
}
if req.NoSpent != "" {
noSpent, err = req.NoSpent.Int64()
if err == nil && noSpent != 0 {
ctx = context.WithValue(ctx, ctxNoSpent, true)
}
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Process params given in post body for an addrs Utxo endpoint
func (c *insightApiContext) PostAddrsUtxoCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := apitypes.InsightAddr{}
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeInsightError(w, fmt.Sprintf("error reading JSON message: %v", err))
return
}
err = json.Unmarshal(body, &req)
if err != nil {
writeInsightError(w, fmt.Sprintf("Failed to parse request: %v", err))
return
}
// Successful extraction of Body JSON
ctx := context.WithValue(r.Context(), m.CtxAddress, req.Addrs)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// AddressCommandCtx returns a http.HandlerFunc that embeds the value at the url
// part {command} into the request context.
func (c *insightApiContext) AddressCommandCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
command := chi.URLParam(r, "command")
ctx := context.WithValue(r.Context(), ctxAddrCmd, command)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetAddressCommandCtx retrieves the ctxAddrCmd data from the request context.
// If not set the return value is "" and false.
func (c *insightApiContext) GetAddressCommandCtx(r *http.Request) (string, bool) {
command, ok := r.Context().Value(ctxAddrCmd).(string)
if !ok {
return "", false
}
return command, true
}
// BlockIndexOrHashPathCtx returns a http.HandlerFunc that embeds the value at
// the url part {idxorhash} into the request context.
func (c *insightApiContext) BlockIndexOrHashPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ctx context.Context
pathIdxOrHashStr := chi.URLParam(r, "idxorhash")
if len(pathIdxOrHashStr) == 2*chainhash.HashSize {
ctx = context.WithValue(r.Context(), ctxBlockHash, pathIdxOrHashStr)
} else {
idx, err := strconv.Atoi(pathIdxOrHashStr)
if err != nil {
writeInsightError(w, "Valid hash or index not found")
return
}
ctx = context.WithValue(r.Context(), ctxBlockIndex, idx)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetInsightBlockIndexCtx retrieves the ctxBlockIndex data from the request context. If not
// set, the return value is an 0 and false
func (c *insightApiContext) GetInsightBlockIndexCtx(r *http.Request) (int, bool) {
idx, ok := r.Context().Value(ctxBlockIndex).(int)
if !ok {
apiLog.Trace("Rawtx hex transaction not set")
return 0, false
}
return idx, true
}
// GetInsightBlockHashCtx retrieves the ctxBlockHash data from the request context. If not
// set, the return value is an empty string and false
func (c *insightApiContext) GetInsightBlockHashCtx(r *http.Request) (string, bool) {
hash, ok := r.Context().Value(ctxBlockHash).(string)
if !ok {
apiLog.Trace("Rawtx hex transaction not set")
return "", false
}
return hash, true
}
// NoTxListCtx returns a http.Handlerfunc that embeds the {noTxList} value in
// the request into the request context.
func (c *insightApiContext) NoTxListCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
notxlist := r.FormValue("noTxList")
notxlistint, err := strconv.Atoi(notxlist)
if err != nil {
notxlistint = 0
}
ctx := context.WithValue(r.Context(), ctxNoTxList, notxlistint)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetLimitCtx retrieves the ctxLimit data from the request context. If not set,
// the return value is 0 which is interpreted as no limit.
func (c *insightApiContext) GetLimitCtx(r *http.Request) int {
limit, ok := r.Context().Value(m.CtxLimit).(string)
if !ok {
return 0
}
intValue, err := strconv.Atoi(limit)
if err != nil {
return 0
}
return intValue
}
// GetNoTxListCtx retrieves the ctxNoTxList data ("noTxList") from the request context.
// If not set, the return value is false.
func (c *insightApiContext) GetNoTxListCtx(r *http.Request) int {
notxlist, ok := r.Context().Value(ctxNoTxList).(int)
if !ok {
return 0
}
return notxlist
}
// BlockDateLimitQueryCtx returns a http.Handlerfunc that embeds the
// {blockdate,limit} value in the request into the request context.
func (c *insightApiContext) BlockDateLimitQueryCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
blockDate := r.FormValue("blockDate")
ctx := context.WithValue(r.Context(), m.CtxBlockDate, blockDate)
limit := r.FormValue("limit")
ctx = context.WithValue(ctx, m.CtxLimit, limit)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetNbBlocksCtx retrieves the ctxNbBlocks data from the request context. If not
// set, the return value is 0.
func (c *insightApiContext) GetNbBlocksCtx(r *http.Request) int {
nbBlocks, ok := r.Context().Value(ctxNbBlocks).(int)
if !ok {
return 0
}
return nbBlocks
}
// NbBlocksCtx will parse the query parameters for nbBlocks.
func (c *insightApiContext) NbBlocksCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
nbBlocks := r.FormValue("nbBlocks")
nbBlocksint, err := strconv.Atoi(nbBlocks)
if err == nil {
ctx = context.WithValue(r.Context(), ctxNbBlocks, nbBlocksint)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}