forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 1
/
apimiddleware.go
622 lines (562 loc) · 18.7 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package middleware
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
apitypes "github.com/decred/dcrdata/api/types"
"github.com/go-chi/chi"
"github.com/go-chi/docgen"
)
type contextKey int
const (
ctxAPIDocs contextKey = iota
ctxAPIStatus
CtxAddress
ctxBlockIndex0
ctxBlockIndex
ctxBlockStep
ctxBlockHash
ctxTxHash
ctxTxns
ctxTxInOutIndex
ctxSearch
ctxN
ctxCount
ctxOffset
CtxBlockDate
CtxLimit
ctxGetStatus
ctxStakeVersionLatest
ctxRawHexTx
ctxM
)
type DataSource interface {
GetHeight() int
GetBlockHeight(hash string) (int64, error)
GetBlockHash(idx int64) (string, error)
}
type StakeVersionsLatest func() (*dcrjson.StakeVersions, error)
// GetBlockStepCtx retrieves the ctxBlockStep data from the request context. If
// not set, the return value is -1.
func GetBlockStepCtx(r *http.Request) int {
step, ok := r.Context().Value(ctxBlockStep).(int)
if !ok {
apiLog.Error("block step not set")
return -1
}
return step
}
// GetBlockStepCtx retrieves the ctxBlockIndex0 data from the request context.
// If not set, the return value is -1.
func GetBlockIndex0Ctx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex0).(int)
if !ok {
apiLog.Error("block index0 not set")
return -1
}
return idx
}
// GetTxIOIndexCtx retrieves the ctxTxInOutIndex data from the request context.
// If not set, the return value is -1.
func GetTxIOIndexCtx(r *http.Request) int {
index, ok := r.Context().Value(ctxTxInOutIndex).(int)
if !ok {
apiLog.Trace("txinoutindex not set")
return -1
}
return index
}
// GetNCtx retrieves the ctxN data from the request context. If not set, the
// return value is -1.
func GetNCtx(r *http.Request) int {
N, ok := r.Context().Value(ctxN).(int)
if !ok {
apiLog.Trace("N not set")
return -1
}
return N
}
// GetMCtx retrieves the ctxM data from the request context. If not set, the
// return value is -1.
func GetMCtx(r *http.Request) int {
M, ok := r.Context().Value(ctxM).(int)
if !ok {
apiLog.Trace("M not set")
return -1
}
return M
}
// GetRawHexTx retrieves the ctxRawHexTx data from the request context. If not
// set, the return value is an empty string.
func GetRawHexTx(r *http.Request) string {
rawHexTx, ok := r.Context().Value(ctxRawHexTx).(string)
if !ok {
apiLog.Trace("hex transaction id not set")
return ""
}
return rawHexTx
}
// GetTxIDCtx retrieves the ctxTxHash data from the request context. If not set,
// the return value is an empty string.
func GetTxIDCtx(r *http.Request) string {
hash, ok := r.Context().Value(ctxTxHash).(string)
if !ok {
apiLog.Trace("txid not set")
return ""
}
return hash
}
// GetTxnsCtx retrieves the ctxTxns data from the request context. If not set,
// the return value is an empty string slice.
func GetTxnsCtx(r *http.Request) []string {
hashes, ok := r.Context().Value(ctxTxns).([]string)
if !ok {
apiLog.Trace("ctxTxns not set")
return nil
}
return hashes
}
// PostTxnsCtx extract transaction IDs from the POST body
func PostTxnsCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := apitypes.Txns{}
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
apiLog.Debugf("No/invalid txns: %v", err)
http.Error(w, "error reading JSON message", http.StatusBadRequest)
return
}
err = json.Unmarshal(body, &req)
if err != nil {
apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err)
http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest)
return
}
// Successful extraction of body JSON
ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// ValidateTxnsPostCtx will confirm Post content length is valid.
func ValidateTxnsPostCtx(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 {
http.Error(w, "Unable to parse Content-Length", http.StatusBadRequest)
return
}
// Broadcast Tx has the largest possible body.
maxPayload := 1 << 22
if contentLength > maxPayload {
http.Error(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload), http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
}
// GetBlockHashCtx retrieves the ctxBlockHash data from the request context. If
// not set, the return value is an empty string.
func GetBlockHashCtx(r *http.Request) string {
hash, ok := r.Context().Value(ctxBlockHash).(string)
if !ok {
apiLog.Trace("block hash not set")
}
return hash
}
// GetAddressCtx retrieves the ctxAddress data from the request context. If not
// set, the return value is an empty string.
func GetAddressCtx(r *http.Request) string {
address, ok := r.Context().Value(CtxAddress).(string)
if !ok {
apiLog.Trace("address not set")
return ""
}
return address
}
// GetCountCtx retrieves the ctxCount data ("to") URL path element from the
// request context. If not set, the return value is 20. TODO: rename this
// function.
func GetCountCtx(r *http.Request) int {
count, ok := r.Context().Value(ctxCount).(int)
if !ok {
apiLog.Trace("count not set")
return 20
}
return count
}
// GetCountCtx retrieves the ctxOffset data ("from") from the request context.
// If not set, the return value is 0. TODO: rename this function.
func GetOffsetCtx(r *http.Request) int {
offset, ok := r.Context().Value(ctxOffset).(int)
if !ok {
apiLog.Trace("offset not set")
return 0
}
return offset
}
// GetStatusInfoCtx retrieves the ctxGetStatus data ("q" POST form data) from
// the request context. If not set, the return value is an empty string.
func GetStatusInfoCtx(r *http.Request) string {
statusInfo, ok := r.Context().Value(ctxGetStatus).(string)
if !ok {
apiLog.Error("status info no set")
return ""
}
return statusInfo
}
// GetBlockDateCtx retrieves the ctxBlockDate data from the request context. If
// not set, the return value is an empty string.
func GetBlockDateCtx(r *http.Request) string {
blockDate, _ := r.Context().Value(CtxBlockDate).(string)
return blockDate
}
// GetBlockIndexCtx retrieves the ctxBlockIndex data from the request context.
// If not set, the return -1.
func GetBlockIndexCtx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex).(int)
if !ok {
apiLog.Trace("block index not set")
return -1
}
return idx
}
// CacheControl creates a new middleware to set the HTTP response header with
// "Cache-Control: max-age=maxAge" where maxAge is in seconds.
func CacheControl(maxAge int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age="+strconv.FormatInt(maxAge, 10))
next.ServeHTTP(w, r)
})
}
}
// BlockStepPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {step} into the request context.
func BlockStepPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
stepIdxStr := chi.URLParam(r, "step")
step, err := strconv.Atoi(stepIdxStr)
if err != nil {
apiLog.Infof("No/invalid step value (int64): %v", err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxBlockStep, step)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockIndexPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {idx} into the request context.
func BlockIndexPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathIdxStr := chi.URLParam(r, "idx")
idx, err := strconv.Atoi(pathIdxStr)
if err != nil {
apiLog.Infof("No/invalid idx value (int64): %v", err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxBlockIndex, idx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockIndexOrHashPathCtx returns a http.HandlerFunc that embeds the value at
// the url part {idxorhash} into the request context.
func 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 {
apiLog.Infof("No/invalid idx value (int64): %v", err)
http.NotFound(w, r)
return
}
ctx = context.WithValue(r.Context(), ctxBlockIndex, idx)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockIndex0PathCtx returns a http.HandlerFunc that embeds the value at the
// url part {idx0} into the request context.
func BlockIndex0PathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathIdxStr := chi.URLParam(r, "idx0")
idx, err := strconv.Atoi(pathIdxStr)
if err != nil {
apiLog.Infof("No/invalid idx0 value (int64): %v", err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxBlockIndex0, idx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// NPathCtx returns a http.HandlerFunc that embeds the value at the url part {N}
// into the request context.
func NPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathNStr := chi.URLParam(r, "N")
N, err := strconv.Atoi(pathNStr)
if err != nil {
apiLog.Infof("No/invalid numeric value (uint64): %v", err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxN, N)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// MPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {M} into the request context
func MPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathMStr := chi.URLParam(r, "M")
M, err := strconv.Atoi(pathMStr)
if err != nil {
apiLog.Infof("No/invalid numeric value (uint64): %v", err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxM, M)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockHashPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {blockhash} into the request context.
func BlockHashPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hash := chi.URLParam(r, "blockhash")
ctx := context.WithValue(r.Context(), ctxBlockHash, hash)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// TransactionHashCtx returns a http.HandlerFunc that embeds the value at the
// url part {txid} into the request context.
func TransactionHashCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
txid := chi.URLParam(r, "txid")
ctx := context.WithValue(r.Context(), ctxTxHash, txid)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// TransactionIOIndexCtx returns a http.HandlerFunc that embeds the value at the
// url part {txinoutindex} into the request context
func TransactionIOIndexCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
idxStr := chi.URLParam(r, "txinoutindex")
idx, err := strconv.Atoi(idxStr)
if err != nil {
apiLog.Infof("No/invalid numeric value (%v): %v", idxStr, err)
http.NotFound(w, r)
return
}
ctx := context.WithValue(r.Context(), ctxTxInOutIndex, idx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// AddressPathCtx returns a http.HandlerFunc that embeds the value at the url
// part {address} into the request context.
func AddressPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
address := chi.URLParam(r, "address")
ctx := context.WithValue(r.Context(), CtxAddress, address)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// apiDocs generates a middleware with a "docs" in the context containing a map
// of the routers handlers, etc.
func apiDocs(mux *chi.Mux) func(next http.Handler) http.Handler {
var buf bytes.Buffer
json.Indent(&buf, []byte(docgen.JSONRoutesDoc(mux)), "", "\t")
docs := buf.String()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ctxAPIDocs, docs)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// SearchPathCtx returns a http.HandlerFunc that embeds the value at the url part
// {search} into the request context (Still need this for the error page)
// TODO: make new error system
func SearchPathCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
str := chi.URLParam(r, "search")
ctx := context.WithValue(r.Context(), ctxSearch, str)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// APIDirectory is the actual handler used with apiDocs
// (e.g. mux.With(apiDocs(mux)).HandleFunc("/help", APIDirectory))
func APIDirectory(w http.ResponseWriter, r *http.Request) {
docs := r.Context().Value(ctxAPIDocs).(string)
io.WriteString(w, docs)
}
// TransactionsCtx returns a http.Handlerfunc that embeds the {address,
// blockhash} value in the request into the request context.
func TransactionsCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
address := r.FormValue("address")
if address != "" {
ctx := context.WithValue(r.Context(), CtxAddress, address)
next.ServeHTTP(w, r.WithContext(ctx))
}
hash := r.FormValue("block")
if hash != "" {
ctx := context.WithValue(r.Context(), ctxBlockHash, hash)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}
// PaginationCtx returns a http.Handlerfunc that embeds the {to,from} value in
// the request into the request context.
func PaginationCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
to, from := r.FormValue("to"), r.FormValue("from")
if to == "" {
to = "20"
}
if from == "" {
from = "0"
}
offset, err := strconv.Atoi(from)
if err != nil {
http.Error(w, "invalid from value", 422)
return
}
count, err := strconv.Atoi(to)
if err != nil {
http.Error(w, "invalid to value", 422)
return
}
ctx := context.WithValue(r.Context(), ctxCount, count)
ctx = context.WithValue(ctx, ctxOffset, offset)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// AddressPostCtx returns a http.HandlerFunc that embeds the {addrs} value in
// the post request into the request context.
func AddressPostCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
address := r.PostFormValue("addrs")
ctx := context.WithValue(r.Context(), CtxAddress, address)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockDateQueryCtx returns a http.Handlerfunc that embeds the {blockdate,
// limit} value in the request into the request context.
func BlockDateQueryCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
blockDate := r.FormValue("blockDate")
limit := r.FormValue("limit")
if blockDate == "" {
http.Error(w, "invalid block date", 422)
return
}
fmt.Println("limit in block query ", limit)
ctx := context.WithValue(r.Context(), CtxBlockDate, blockDate)
ctx = context.WithValue(ctx, CtxLimit, limit)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// BlockHashPathAndIndexCtx embeds the value at the url part {blockhash}, and
// the corresponding block index, into a request context.
func BlockHashPathAndIndexCtx(r *http.Request, source DataSource) context.Context {
hash := chi.URLParam(r, "blockhash")
height, err := source.GetBlockHeight(hash)
if err != nil {
apiLog.Errorf("Unable to GetBlockHeight(%d): %v", height, err)
}
ctx := context.WithValue(r.Context(), ctxBlockHash, hash)
return context.WithValue(ctx, ctxBlockIndex, height)
}
// StatusInfoCtx embeds the best block index and the POST form data for
// parameter "q" into a request context.
func StatusInfoCtx(r *http.Request, source DataSource) context.Context {
idx := -1
if source.GetHeight() >= 0 {
idx = source.GetHeight()
}
ctx := context.WithValue(r.Context(), ctxBlockIndex, idx)
q := r.FormValue("q")
return context.WithValue(ctx, ctxGetStatus, q)
}
// BlockHashLatestCtx embeds the current block height and hash into a request
// context.
func BlockHashLatestCtx(r *http.Request, source DataSource) context.Context {
var hash string
// if hash, err = c.BlockData.GetBestBlockHash(int64(idx)); err != nil {
// apiLog.Errorf("Unable to GetBestBlockHash: %v", idx, err)
// }
idx := source.GetHeight()
if idx >= 0 {
var err error
if hash, err = source.GetBlockHash(int64(idx)); err != nil {
apiLog.Errorf("Unable to GetBlockHash(%d): %v", idx, err)
}
}
ctx := context.WithValue(r.Context(), ctxBlockIndex, idx)
return context.WithValue(ctx, ctxBlockHash, hash)
}
// StakeVersionLatestCtx embeds the specified StakeVersionsLatest function into
// a request context.
func StakeVersionLatestCtx(r *http.Request, stakeVerFun StakeVersionsLatest) context.Context {
ver := -1
stkVers, err := stakeVerFun()
if err == nil && stkVers != nil {
ver = int(stkVers.StakeVersion)
}
return context.WithValue(r.Context(), ctxStakeVersionLatest, ver)
}
// BlockIndexLatestCtx embeds the current block height into a request context.
func BlockIndexLatestCtx(r *http.Request, source DataSource) context.Context {
idx := -1
if source.GetHeight() >= 0 {
idx = source.GetHeight()
}
return context.WithValue(r.Context(), ctxBlockIndex, idx)
}
// StatusCtx embeds the specified apitypes.Status into a request context.
func StatusCtx(r *http.Request, status apitypes.Status) context.Context {
return context.WithValue(r.Context(), ctxAPIStatus, status)
}
// GetBlockHeightCtx returns the block height for the block index or hash
// specified on the URL path.
func GetBlockHeightCtx(r *http.Request, source DataSource) int64 {
idxI, ok := r.Context().Value(ctxBlockIndex).(int)
idx := int64(idxI)
if !ok || idx < 0 {
var err error
idx, err = source.GetBlockHeight(GetBlockHashCtx(r))
if err != nil {
apiLog.Errorf("Unable to GetBlockHeight: %v", err)
}
}
return idx
}
// GetLatestVoteVersionCtx attempts to retrieve the latest stake version
// embedded in the request context.
func GetLatestVoteVersionCtx(r *http.Request) int {
ver, ok := r.Context().Value(ctxStakeVersionLatest).(int)
if !ok {
apiLog.Error("latest stake version not set")
return -1
}
return ver
}