forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiroutes.go
1084 lines (937 loc) · 27.8 KB
/
apiroutes.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"sync"
apitypes "github.com/dcrdata/dcrdata/dcrdataapi"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/rpcclient"
)
// APIDataSource implements an interface for collecting data for the api
type APIDataSource interface {
GetHeight() int
GetBestBlockHash() (string, error)
GetBlockHash(idx int64) (string, error)
GetBlockHeight(hash string) (int64, error)
//Get(idx int) *blockdata.BlockData
GetHeader(idx int) *dcrjson.GetBlockHeaderVerboseResult
GetBlockVerbose(idx int, verboseTx bool) *dcrjson.GetBlockVerboseResult
GetBlockVerboseByHash(hash string, verboseTx bool) *dcrjson.GetBlockVerboseResult
GetRawTransaction(txid string) *apitypes.Tx
GetTransactionHex(txid string) string
GetTrimmedTransaction(txid string) *apitypes.TrimmedTx
GetRawTransactionWithPrevOutAddresses(txid string) (*apitypes.Tx, [][]string)
GetVoteInfo(txid string) (*apitypes.VoteInfo, error)
GetVoteVersionInfo(ver uint32) (*dcrjson.GetVoteInfoResult, error)
GetStakeVersions(txHash string, count int32) (*dcrjson.GetStakeVersionsResult, error)
GetStakeVersionsLatest() (*dcrjson.StakeVersions, error)
GetAllTxIn(txid string) []*apitypes.TxIn
GetAllTxOut(txid string) []*apitypes.TxOut
GetTransactionsForBlock(idx int64) *apitypes.BlockTransactions
GetTransactionsForBlockByHash(hash string) *apitypes.BlockTransactions
GetFeeInfo(idx int) *dcrjson.FeeInfoBlock
//GetStakeDiffEstimate(idx int) *dcrjson.EstimateStakeDiffResult
GetStakeInfoExtended(idx int) *apitypes.StakeInfoExtended
//needs db update: GetStakeInfoExtendedByHash(hash string) *apitypes.StakeInfoExtended
GetStakeDiffEstimates() *apitypes.StakeDiff
//GetBestBlock() *blockdata.BlockData
GetSummary(idx int) *apitypes.BlockDataBasic
GetSummaryByHash(hash string) *apitypes.BlockDataBasic
GetBestBlockSummary() *apitypes.BlockDataBasic
GetBlockSize(idx int) (int32, error)
GetBlockSizeRange(idx0, idx1 int) ([]int32, error)
GetPoolInfo(idx int) *apitypes.TicketPoolInfo
GetPoolInfoByHash(hash string) *apitypes.TicketPoolInfo
GetPoolInfoRange(idx0, idx1 int) []apitypes.TicketPoolInfo
GetPool(idx int64) ([]string, error)
GetPoolByHash(hash string) ([]string, error)
GetPoolValAndSizeRange(idx0, idx1 int) ([]float64, []float64)
GetSDiff(idx int) float64
GetSDiffRange(idx0, idx1 int) []float64
GetMempoolSSTxSummary() *apitypes.MempoolTicketFeeInfo
GetMempoolSSTxFeeRates(N int) *apitypes.MempoolTicketFees
GetMempoolSSTxDetails(N int) *apitypes.MempoolTicketDetails
GetAddressTransactions(addr string, count int) *apitypes.Address
GetAddressTransactionsRaw(addr string, count int) []*apitypes.AddressTxRaw
}
// dcrdata application context used by all route handlers
type appContext struct {
nodeClient *rpcclient.Client
BlockData APIDataSource
Status apitypes.Status
statusMtx sync.RWMutex
JSONIndent string
}
// Constructor for appContext
func newContext(client *rpcclient.Client, blockData APIDataSource, JSONIndent string) *appContext {
conns, _ := client.GetConnectionCount()
nodeHeight, _ := client.GetBlockCount()
return &appContext{
nodeClient: client,
BlockData: blockData,
Status: apitypes.Status{
Height: uint32(nodeHeight),
NodeConnections: conns,
APIVersion: APIVersion,
DcrdataVersion: ver.String(),
},
JSONIndent: JSONIndent,
}
}
func (c *appContext) StatusNtfnHandler(wg *sync.WaitGroup, quit chan struct{}) {
defer wg.Done()
out:
for {
keepon:
select {
case height, ok := <-ntfnChans.updateStatusNodeHeight:
if !ok {
log.Warnf("Block connected channel closed.")
break out
}
c.statusMtx.Lock()
c.Status.Height = height
var err error
c.Status.NodeConnections, err = c.nodeClient.GetConnectionCount()
if err != nil {
c.Status.Ready = false
c.statusMtx.Unlock()
log.Warn("Failed to get connection count: ", err)
break keepon
}
c.statusMtx.Unlock()
case height, ok := <-ntfnChans.updateStatusDBHeight:
if !ok {
log.Warnf("Block connected channel closed.")
break out
}
if c.BlockData == nil {
panic("BlockData APIDataSource is nil")
}
summary := c.BlockData.GetBestBlockSummary()
if summary == nil {
log.Errorf("BlockData summary is nil")
break keepon
}
bdHeight := c.BlockData.GetHeight()
c.statusMtx.Lock()
if bdHeight >= 0 && summary.Height == uint32(bdHeight) &&
height == uint32(bdHeight) {
c.Status.DBHeight = height
// if DB height agrees with node height, then we're ready
if c.Status.Height == height {
c.Status.Ready = true
} else {
c.Status.Ready = false
}
c.statusMtx.Unlock()
break keepon
}
c.Status.Ready = false
c.statusMtx.Unlock()
log.Errorf("New DB height (%d) and stored block data (%d, %d) not consistent.",
height, bdHeight, summary.Height)
case _, ok := <-quit:
if !ok {
log.Debugf("Got quit signal. Exiting block connected handler for STATUS monitor.")
break out
}
}
}
}
// root is a http.Handler intended for the API root path. This essentially
// provides a heartbeat, and no information about the application status.
func (c *appContext) root(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "dcrdata api running")
}
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
}
func getBlockIndexCtx(r *http.Request) int {
idx, ok := r.Context().Value(ctxBlockIndex).(int)
if !ok {
apiLog.Error("block index not set")
return -1
}
return idx
}
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
}
func getBlockHashOnlyCtx(r *http.Request) string {
hash, ok := r.Context().Value(ctxBlockHash).(string)
if !ok {
apiLog.Trace("block hash not set")
return ""
}
return hash
}
func (c *appContext) getBlockHashCtx(r *http.Request) string {
hash := getBlockHashOnlyCtx(r)
if hash == "" {
var err error
hash, err = c.BlockData.GetBlockHash(int64(getBlockIndexCtx(r)))
if err != nil {
apiLog.Errorf("Unable to GetBlockHash: %v", err)
}
}
return hash
}
func (c *appContext) getBlockHeightCtx(r *http.Request) int64 {
idxI, ok := r.Context().Value(ctxBlockIndex).(int)
idx := int64(idxI)
if !ok || idx < 0 {
var err error
idx, err = c.BlockData.GetBlockHeight(getBlockHashOnlyCtx(r))
if err != nil {
apiLog.Errorf("Unable to GetBlockHeight: %v", err)
}
}
return idx
}
func getTxIDCtx(r *http.Request) string {
hash, ok := r.Context().Value(ctxTxHash).(string)
if !ok {
apiLog.Trace("txid not set")
return ""
}
return hash
}
func getTxIOIndexCtx(r *http.Request) int {
index, ok := r.Context().Value(ctxTxInOutIndex).(int)
if !ok {
apiLog.Trace("txinoutindex not set")
return -1
}
return index
}
func getAddressCtx(r *http.Request) string {
address, ok := r.Context().Value(ctxAddress).(string)
if !ok {
apiLog.Trace("address not set")
return ""
}
return address
}
func getNCtx(r *http.Request) int {
N, ok := r.Context().Value(ctxN).(int)
if !ok {
apiLog.Trace("N not set")
return -1
}
return N
}
func getStatusCtx(r *http.Request) *apitypes.Status {
status, ok := r.Context().Value(ctxAPIStatus).(*apitypes.Status)
if !ok {
apiLog.Error("apitypes.Status not set")
return nil
}
return status
}
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
}
func (c *appContext) writeJSONHandlerFunc(thing interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, thing, c.JSONIndent)
}
}
func writeJSON(w http.ResponseWriter, thing interface{}, indent string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
encoder.SetIndent("", indent)
if err := encoder.Encode(thing); err != nil {
apiLog.Infof("JSON encode error: %v", err)
}
}
func (c *appContext) getIndentQuery(r *http.Request) (indent string) {
useIndentation := r.URL.Query().Get("indent")
if useIndentation == "1" || useIndentation == "true" {
indent = c.JSONIndent
}
return
}
func getVoteVersionQuery(r *http.Request) (int32, string, error) {
verLatest := int64(getLatestVoteVersionCtx(r))
voteVersion := r.URL.Query().Get("version")
if voteVersion == "" {
return int32(verLatest), voteVersion, nil
}
ver, err := strconv.ParseInt(voteVersion, 10, 0)
if err != nil {
return -1, voteVersion, err
}
if ver > verLatest {
ver = verLatest
}
return int32(ver), voteVersion, nil
}
func (c *appContext) status(w http.ResponseWriter, r *http.Request) {
c.statusMtx.RLock()
defer c.statusMtx.RUnlock()
writeJSON(w, c.Status, c.getIndentQuery(r))
}
func (c *appContext) currentHeight(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := io.WriteString(w, strconv.Itoa(int(c.Status.Height))); err != nil {
apiLog.Infof("failed to write height response: %v", err)
}
}
func (c *appContext) getLatestBlock(w http.ResponseWriter, r *http.Request) {
latestBlockSummary := c.BlockData.GetBestBlockSummary()
if latestBlockSummary == nil {
apiLog.Error("Unable to get latest block summary")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, latestBlockSummary, c.getIndentQuery(r))
}
func (c *appContext) getBlockHeight(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := io.WriteString(w, strconv.Itoa(int(idx))); err != nil {
apiLog.Infof("failed to write height response: %v", err)
}
}
func (c *appContext) getBlockHash(w http.ResponseWriter, r *http.Request) {
hash := c.getBlockHashCtx(r)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := io.WriteString(w, hash); err != nil {
apiLog.Infof("failed to write height response: %v", err)
}
}
func (c *appContext) getBlockSummary(w http.ResponseWriter, r *http.Request) {
// attempt to get hash of block set by hash or (fallback) height set on path
hash := c.getBlockHashCtx(r)
if hash == "" {
http.Error(w, http.StatusText(422), 422)
return
}
blockSummary := c.BlockData.GetSummaryByHash(hash)
if blockSummary == nil {
apiLog.Errorf("Unable to get block %s summary", hash)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockSummary, c.getIndentQuery(r))
}
func (c *appContext) getBlockTransactions(w http.ResponseWriter, r *http.Request) {
hash := c.getBlockHashCtx(r)
if hash == "" {
http.Error(w, http.StatusText(422), 422)
return
}
blockTransactions := c.BlockData.GetTransactionsForBlockByHash(hash)
if blockTransactions == nil {
apiLog.Errorf("Unable to get block %s transactions", hash)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockTransactions, c.getIndentQuery(r))
}
func (c *appContext) getBlockTransactionsCount(w http.ResponseWriter, r *http.Request) {
hash := c.getBlockHashCtx(r)
if hash == "" {
http.Error(w, http.StatusText(422), 422)
return
}
blockTransactions := c.BlockData.GetTransactionsForBlockByHash(hash)
if blockTransactions == nil {
apiLog.Errorf("Unable to get block %s transactions", hash)
return
}
writeJSON(w, &struct {
Tx int `json:"tx"`
STx int `json:"stx"`
}{len(blockTransactions.Tx), len(blockTransactions.STx)}, c.getIndentQuery(r))
}
func (c *appContext) getBlockHeader(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
blockHeader := c.BlockData.GetHeader(int(idx))
if blockHeader == nil {
apiLog.Errorf("Unable to get block %d header", idx)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockHeader, c.getIndentQuery(r))
}
func (c *appContext) getBlockVerbose(w http.ResponseWriter, r *http.Request) {
hash := c.getBlockHashCtx(r)
if hash == "" {
http.Error(w, http.StatusText(422), 422)
return
}
blockVerbose := c.BlockData.GetBlockVerboseByHash(hash, false)
if blockVerbose == nil {
apiLog.Errorf("Unable to get block %s", hash)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockVerbose, c.getIndentQuery(r))
}
func (c *appContext) getVoteInfo(w http.ResponseWriter, r *http.Request) {
ver, verStr, err := getVoteVersionQuery(r)
if err != nil || ver < 0 {
apiLog.Errorf("Unable to get vote info for stake version %s", verStr)
http.Error(w, "Unable to get vote info for stake version "+verStr, 422)
return
}
voteVersionInfo, err := c.BlockData.GetVoteVersionInfo(uint32(ver))
if err != nil || voteVersionInfo == nil {
apiLog.Errorf("Unable to get vote version %d info: %v", ver, err)
http.Error(w, "Unable to get vote info for stake version "+verStr, 422)
return
}
writeJSON(w, voteVersionInfo, c.getIndentQuery(r))
}
func (c *appContext) getTransaction(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
tx := c.BlockData.GetRawTransaction(txid)
if tx == nil {
apiLog.Errorf("Unable to get transaction %s", txid)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, tx, c.getIndentQuery(r))
}
func (c *appContext) getTransactionHex(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
hex := c.BlockData.GetTransactionHex(txid)
fmt.Fprintf(w, hex)
}
func (c *appContext) getDecodedTx(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
tx := c.BlockData.GetTrimmedTransaction(txid)
if tx == nil {
apiLog.Errorf("Unable to get transaction %s", txid)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, tx, c.getIndentQuery(r))
}
func (c *appContext) getTxVoteInfo(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
vinfo, err := c.BlockData.GetVoteInfo(txid)
if err != nil {
apiLog.Errorf("Unable to get vote info for transaction %s", txid)
http.Error(w, "Unable to get vote info. Is tx "+txid+" a vote?", 422)
return
}
writeJSON(w, vinfo, c.getIndentQuery(r))
}
// getTransactionInputs serves []TxIn
func (c *appContext) getTransactionInputs(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
allTxIn := c.BlockData.GetAllTxIn(txid)
// allTxIn may be empty, but not a nil slice
if allTxIn == nil {
apiLog.Errorf("Unable to get all TxIn for transaction %s", txid)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, allTxIn, c.getIndentQuery(r))
}
// getTransactionInput serves TxIn[i]
func (c *appContext) getTransactionInput(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
index := getTxIOIndexCtx(r)
if index < 0 {
http.NotFound(w, r)
//http.Error(w, http.StatusText(422), 422)
return
}
allTxIn := c.BlockData.GetAllTxIn(txid)
// allTxIn may be empty, but not a nil slice
if allTxIn == nil {
apiLog.Warnf("Unable to get all TxIn for transaction %s", txid)
http.NotFound(w, r)
return
}
if len(allTxIn) <= index {
apiLog.Debugf("Index %d larger than []TxIn length %d", index, len(allTxIn))
http.NotFound(w, r)
return
}
writeJSON(w, *allTxIn[index], c.getIndentQuery(r))
}
// getTransactionOutputs serves []TxOut
func (c *appContext) getTransactionOutputs(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
allTxOut := c.BlockData.GetAllTxOut(txid)
// allTxOut may be empty, but not a nil slice
if allTxOut == nil {
apiLog.Errorf("Unable to get all TxOut for transaction %s", txid)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, allTxOut, c.getIndentQuery(r))
}
// getTransactionOutput serves TxOut[i]
func (c *appContext) getTransactionOutput(w http.ResponseWriter, r *http.Request) {
txid := getTxIDCtx(r)
if txid == "" {
http.Error(w, http.StatusText(422), 422)
return
}
index := getTxIOIndexCtx(r)
if index < 0 {
http.NotFound(w, r)
return
}
allTxOut := c.BlockData.GetAllTxOut(txid)
// allTxOut may be empty, but not a nil slice
if allTxOut == nil {
apiLog.Errorf("Unable to get all TxOut for transaction %s", txid)
http.Error(w, http.StatusText(422), 422)
return
}
if len(allTxOut) <= index {
apiLog.Debugf("Index %d larger than []TxOut length %d", index, len(allTxOut))
http.NotFound(w, r)
return
}
writeJSON(w, *allTxOut[index], c.getIndentQuery(r))
}
func (c *appContext) getBlockFeeInfo(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
blockFeeInfo := c.BlockData.GetFeeInfo(int(idx))
if blockFeeInfo == nil {
apiLog.Errorf("Unable to get block %d fee info", idx)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockFeeInfo, c.getIndentQuery(r))
}
func (c *appContext) getBlockStakeInfoExtended(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
stakeinfo := c.BlockData.GetStakeInfoExtended(int(idx))
if stakeinfo == nil {
apiLog.Errorf("Unable to get block %d fee info", idx)
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, stakeinfo, c.getIndentQuery(r))
}
func (c *appContext) getStakeDiffSummary(w http.ResponseWriter, r *http.Request) {
stakeDiff := c.BlockData.GetStakeDiffEstimates()
if stakeDiff == nil {
apiLog.Errorf("Unable to get stake diff info")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, stakeDiff, c.getIndentQuery(r))
}
func (c *appContext) getStakeDiffCurrent(w http.ResponseWriter, r *http.Request) {
stakeDiff := c.BlockData.GetStakeDiffEstimates()
if stakeDiff == nil {
apiLog.Errorf("Unable to get stake diff info")
http.Error(w, http.StatusText(422), 422)
return
}
stakeDiffCurrent := dcrjson.GetStakeDifficultyResult{
CurrentStakeDifficulty: stakeDiff.CurrentStakeDifficulty,
NextStakeDifficulty: stakeDiff.NextStakeDifficulty,
}
writeJSON(w, stakeDiffCurrent, c.getIndentQuery(r))
}
func (c *appContext) getStakeDiffEstimates(w http.ResponseWriter, r *http.Request) {
stakeDiff := c.BlockData.GetStakeDiffEstimates()
if stakeDiff == nil {
apiLog.Errorf("Unable to get stake diff info")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, stakeDiff.Estimates, c.getIndentQuery(r))
}
func (c *appContext) getSSTxSummary(w http.ResponseWriter, r *http.Request) {
sstxSummary := c.BlockData.GetMempoolSSTxSummary()
if sstxSummary == nil {
apiLog.Errorf("Unable to get SSTx info from mempool")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, sstxSummary, c.getIndentQuery(r))
}
func (c *appContext) getSSTxFees(w http.ResponseWriter, r *http.Request) {
N := getNCtx(r)
sstxFees := c.BlockData.GetMempoolSSTxFeeRates(N)
if sstxFees == nil {
apiLog.Errorf("Unable to get SSTx fees from mempool")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, sstxFees, c.getIndentQuery(r))
}
func (c *appContext) getSSTxDetails(w http.ResponseWriter, r *http.Request) {
N := getNCtx(r)
sstxDetails := c.BlockData.GetMempoolSSTxDetails(N)
if sstxDetails == nil {
apiLog.Errorf("Unable to get SSTx details from mempool")
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, sstxDetails, c.getIndentQuery(r))
}
func (c *appContext) getBlockSize(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
blockSize, err := c.BlockData.GetBlockSize(int(idx))
if err != nil {
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockSize, "")
}
func (c *appContext) getBlockRangeSize(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 || idx < idx0 {
http.Error(w, http.StatusText(422), 422)
return
}
blockSizes, err := c.BlockData.GetBlockSizeRange(idx0, idx)
if err != nil {
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, blockSizes, "")
}
func (c *appContext) getBlockRangeSteppedSize(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 || idx < idx0 {
http.Error(w, http.StatusText(422), 422)
return
}
step := getBlockStepCtx(r)
if step <= 0 {
http.Error(w, "Yeaaah, that step's not gonna work with me.", 422)
return
}
blockSizesFull, err := c.BlockData.GetBlockSizeRange(idx0, idx)
if err != nil {
http.Error(w, http.StatusText(422), 422)
return
}
var blockSizes []int32
if step == 1 {
blockSizes = blockSizesFull
} else {
numValues := (idx - idx0 + 1) / step
blockSizes = make([]int32, 0, numValues)
for i := idx0; i <= idx; i += step {
blockSizes = append(blockSizes, blockSizesFull[i-idx0])
}
// it's the client's problem if i doesn't go all the way to idx
}
writeJSON(w, blockSizes, "")
}
func (c *appContext) getBlockRangeSummary(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
// TODO: check that we have all in range
// N := idx - idx0 + 1
// summaries := make([]*apitypes.BlockDataBasic, 0, N)
// for i := idx0; i <= idx; i++ {
// summaries = append(summaries, c.BlockData.GetSummary(i))
// }
// writeJSON(w, summaries, c.getIndentQuery(r))
w.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
indent := c.getIndentQuery(r)
prefix, newline := indent, ""
encoder.SetIndent(prefix, indent)
if indent != "" {
newline = "\n"
}
fmt.Fprintf(w, "[%s%s", newline, prefix)
for i := idx0; i <= idx; i++ {
summary := c.BlockData.GetSummary(i)
if summary == nil {
apiLog.Debugf("Unknown block %d", i)
http.Error(w, fmt.Sprintf("I don't know block %d", i), http.StatusNotFound)
return
}
// TODO: deal with the extra newline from Encode, if needed
if err := encoder.Encode(summary); err != nil {
apiLog.Infof("JSON encode error: %v", err)
http.Error(w, http.StatusText(422), 422)
return
}
if i != idx {
fmt.Fprintf(w, ",%s%s", newline, prefix)
}
}
fmt.Fprintf(w, "]")
}
func (c *appContext) getBlockRangeSteppedSummary(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
step := getBlockStepCtx(r)
if step <= 0 {
http.Error(w, "Yeaaah, that step's not gonna work with me.", 422)
return
}
// Compute the last block in the range
numSteps := (idx - idx0) / step
last := idx0 + step*numSteps
// Support reverse list (e.g. 10/0/5 counts down from 10 to 0 in steps of 5)
if idx0 > idx {
step = -step
// TODO: support reverse in other endpoints
}
// Prepare JSON encode for streaming response
w.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
indent := c.getIndentQuery(r)
prefix, newline := indent, ""
encoder.SetIndent(prefix, indent)
if indent != "" {
newline = "\n"
}
// Manually structure outer JSON array
fmt.Fprintf(w, "[%s%s", newline, prefix)
// Go through blocks in list, stop after last (i.e. on last+step)
for i := idx0; i != last+step; i += step {
summary := c.BlockData.GetSummary(i)
if summary == nil {
apiLog.Debugf("Unknown block %d", i)
http.Error(w, fmt.Sprintf("I don't know block %d", i), http.StatusNotFound)
return
}
// TODO: deal with the extra newline from Encode, if needed
if err := encoder.Encode(summary); err != nil {
apiLog.Infof("JSON encode error: %v", err)
http.Error(w, http.StatusText(422), 422)
return
}
// After last block, do not print comma+newline+prefix
if i != last {
fmt.Fprintf(w, ",%s%s", newline, prefix)
}
}
fmt.Fprintf(w, "]")
}
func (c *appContext) getTicketPool(w http.ResponseWriter, r *http.Request) {
// getBlockHeightCtx falls back to try hash if height fails
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
tp, err := c.BlockData.GetPool(idx)
if err != nil {
apiLog.Errorf("Unable to fetch ticket pool: %v", err)
http.Error(w, http.StatusText(422), 422)
return
}
sortPool := r.URL.Query().Get("sort")
if sortPool == "1" || sortPool == "true" {
sort.Strings(tp)
}
writeJSON(w, tp, c.getIndentQuery(r))
}
func (c *appContext) getTicketPoolInfo(w http.ResponseWriter, r *http.Request) {
idx := c.getBlockHeightCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
tpi := c.BlockData.GetPoolInfo(int(idx))
writeJSON(w, tpi, c.getIndentQuery(r))
}
func (c *appContext) getTicketPoolInfoRange(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
useArray := r.URL.Query().Get("arrays")
if useArray == "1" || useArray == "true" {
c.getTicketPoolValAndSizeRange(w, r)
return
}
tpis := c.BlockData.GetPoolInfoRange(idx0, idx)
if tpis == nil {
http.Error(w, "invalid range", http.StatusUnprocessableEntity)
return
}
writeJSON(w, tpis, c.getIndentQuery(r))
}
func (c *appContext) getTicketPoolValAndSizeRange(w http.ResponseWriter, r *http.Request) {
idx0 := getBlockIndex0Ctx(r)
if idx0 < 0 {
http.Error(w, http.StatusText(422), 422)
return
}
idx := getBlockIndexCtx(r)
if idx < 0 {
http.Error(w, http.StatusText(422), 422)
return