/
apiroutes.go
1053 lines (928 loc) · 30.2 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
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package insight
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/rpcclient"
apitypes "github.com/decred/dcrdata/api/types"
"github.com/decred/dcrdata/db/dbtypes"
"github.com/decred/dcrdata/db/dcrpg"
m "github.com/decred/dcrdata/middleware"
"github.com/decred/dcrdata/semver"
"github.com/decred/dcrdata/txhelpers"
)
// DataSourceLite specifies an interface for collecting data from the built-in
// databases (i.e. SQLite, storm, ffldb)
type DataSourceLite interface {
UnconfirmedTxnsForAddress(address string) (*txhelpers.AddressOutpoints, int64, error)
}
type insightApiContext struct {
nodeClient *rpcclient.Client
BlockData *dcrpg.ChainDBRPC
params *chaincfg.Params
MemPool DataSourceLite
Status apitypes.Status
JSONIndent string
}
// NewInsightContext Constructor for insightApiContext
func NewInsightContext(client *rpcclient.Client, blockData *dcrpg.ChainDBRPC, params *chaincfg.Params, memPoolData DataSourceLite, JSONIndent string) *insightApiContext {
conns, _ := client.GetConnectionCount()
nodeHeight, _ := client.GetBlockCount()
version := semver.NewSemver(1, 0, 0)
newContext := insightApiContext{
nodeClient: client,
BlockData: blockData,
params: params,
MemPool: memPoolData,
Status: apitypes.Status{
Height: uint32(nodeHeight),
NodeConnections: conns,
APIVersion: APIVersion,
DcrdataVersion: version.String(),
},
}
return &newContext
}
func (c *insightApiContext) getIndentQuery(r *http.Request) (indent string) {
useIndentation := r.URL.Query().Get("indent")
if useIndentation == "1" || useIndentation == "true" {
indent = c.JSONIndent
}
return
}
// Insight API successful response for JSON return items.
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 writeText(w http.ResponseWriter, str string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// Insight API error response for a BAD REQUEST. This means the request was
// malformed in some way or the request HASH, ADDRESS, BLOCK was not valid.
func writeInsightError(w http.ResponseWriter, str string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, str)
}
// Insight API response for an item NOT FOUND. This means the request was valid
// but no records were found for the item in question. For some endpoints
// responding with an empty array [] is expected such as a transaction query for
// addresses with no transactions.
func writeInsightNotFound(w http.ResponseWriter, str string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, str)
}
func (c *insightApiContext) getTransaction(w http.ResponseWriter, r *http.Request) {
txid := m.GetTxIDCtx(r)
if txid == "" {
apiLog.Errorf("Txid cannot be empty")
writeInsightError(w, fmt.Sprintf("Txid cannot be empty"))
return
}
// Return raw transaction
txOld, err := c.BlockData.GetRawTransaction(txid)
if err != nil {
apiLog.Errorf("Unable to get transaction %s", txid)
writeInsightNotFound(w, fmt.Sprintf("Unable to get transaction (%s)", txid))
return
}
txsOld := []*dcrjson.TxRawResult{txOld}
// convert to insight struct
txsNew, err := c.TxConverter(txsOld)
if err != nil {
apiLog.Errorf("Error Processing Transactions")
writeInsightError(w, fmt.Sprintf("Error Processing Transactions"))
return
}
writeJSON(w, txsNew[0], c.getIndentQuery(r))
}
func (c *insightApiContext) getTransactionHex(w http.ResponseWriter, r *http.Request) {
txid := m.GetTxIDCtx(r)
if txid == "" {
writeInsightError(w, "TxId must not be empty")
return
}
txHex := c.BlockData.GetTransactionHex(txid)
if txHex == "" {
writeInsightNotFound(w, fmt.Sprintf("Unable to get transaction (%s)", txHex))
return
}
hexOutput := &apitypes.InsightRawTx{
Rawtx: txHex,
}
writeJSON(w, hexOutput, c.getIndentQuery(r))
}
func (c *insightApiContext) getBlockSummary(w http.ResponseWriter, r *http.Request) {
// attempt to get hash of block set by hash or (fallback) height set on path
hash, ok := c.GetInsightBlockHashCtx(r)
if !ok {
idx, ok := c.GetInsightBlockIndexCtx(r)
if !ok {
writeInsightError(w, "Must provide an index or block hash")
return
}
var err error
hash, err = c.BlockData.ChainDB.GetBlockHash(int64(idx))
if err != nil {
writeInsightError(w, "Unable to get block hash from index")
return
}
}
blockDcrd := c.BlockData.GetBlockVerboseByHash(hash, false)
if blockDcrd == nil {
writeInsightNotFound(w, "Unable to get block")
return
}
blockSummary := []*dcrjson.GetBlockVerboseResult{blockDcrd}
blockInsight, err := c.DcrToInsightBlock(blockSummary)
if err != nil {
apiLog.Errorf("Unable to process block (%s)", hash)
writeInsightError(w, "Unable to Process Block")
return
}
writeJSON(w, blockInsight, c.getIndentQuery(r))
}
func (c *insightApiContext) getBlockHash(w http.ResponseWriter, r *http.Request) {
idx, ok := c.GetInsightBlockIndexCtx(r)
if !ok {
writeInsightError(w, "No index found in query")
return
}
if idx < 0 || idx > c.BlockData.ChainDB.GetHeight() {
writeInsightError(w, "Block height out of range")
return
}
hash, err := c.BlockData.ChainDB.GetBlockHash(int64(idx))
if err != nil || hash == "" {
writeInsightNotFound(w, "Not found")
return
}
blockOutput := struct {
BlockHash string `json:"blockHash"`
}{
hash,
}
writeJSON(w, blockOutput, c.getIndentQuery(r))
}
func (c *insightApiContext) getBlockChainHashCtx(r *http.Request) *chainhash.Hash {
hash, err := chainhash.NewHashFromStr(c.getBlockHashCtx(r))
if err != nil {
apiLog.Errorf("Failed to parse block hash: %v", err)
return nil
}
return hash
}
func (c *insightApiContext) getRawBlock(w http.ResponseWriter, r *http.Request) {
hash, ok := c.GetInsightBlockHashCtx(r)
if !ok {
idx, ok := c.GetInsightBlockIndexCtx(r)
if !ok {
writeInsightError(w, "Must provide an index or block hash")
return
}
var err error
hash, err = c.BlockData.ChainDB.GetBlockHash(int64(idx))
if err != nil {
writeInsightError(w, "Unable to get block hash from index")
return
}
}
chainHash, err := chainhash.NewHashFromStr(hash)
if err != nil {
writeInsightError(w, fmt.Sprintf("Failed to parse block hash: %v", err))
return
}
blockMsg, err := c.nodeClient.GetBlock(chainHash)
if err != nil {
writeInsightNotFound(w, fmt.Sprintf("Failed to retrieve block %s: %v", chainHash.String(), err))
return
}
var blockHex bytes.Buffer
if err = blockMsg.Serialize(&blockHex); err != nil {
apiLog.Errorf("Failed to serialize block: %v", err)
writeInsightError(w, fmt.Sprintf("Failed to serialize block"))
return
}
blockJSON := struct {
BlockHash string `json:"rawblock"`
}{
hex.EncodeToString(blockHex.Bytes()),
}
writeJSON(w, blockJSON, c.getIndentQuery(r))
}
func (c *insightApiContext) broadcastTransactionRaw(w http.ResponseWriter, r *http.Request) {
// Check for rawtx
rawHexTx, ok := c.GetRawHexTx(r)
if !ok {
// JSON extraction failed or rawtx blank. Error message already returned.
return
}
// Check maximum transaction size
if len(rawHexTx)/2 > c.params.MaxTxSize {
writeInsightError(w, fmt.Sprintf("Rawtx length exceeds maximum allowable characters (%d bytes received)", len(rawHexTx)/2))
return
}
// Broadcast
txid, err := c.BlockData.SendRawTransaction(rawHexTx)
if err != nil {
apiLog.Errorf("Unable to send transaction %s", rawHexTx)
writeInsightError(w, fmt.Sprintf("SendRawTransaction failed: %v", err))
return
}
// Respond with hash of broadcasted transaction
txidJSON := struct {
TxidHash string `json:"rawtx"`
}{
txid,
}
writeJSON(w, txidJSON, c.getIndentQuery(r))
}
func (c *insightApiContext) getAddressesTxnOutput(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r) // Required
if address == "" {
writeInsightError(w, "Address cannot be empty")
return
}
// Allow Addresses to be single or multiple separated by a comma.
addresses := strings.Split(address, ",")
// Initialize Output Structure
txnOutputs := make([]apitypes.AddressTxnOutput, 0)
for _, address := range addresses {
confirmedTxnOutputs := c.BlockData.ChainDB.GetAddressUTXO(address)
addressOuts, _, err := c.MemPool.UnconfirmedTxnsForAddress(address)
if err != nil {
apiLog.Errorf("Error in getting unconfirmed transactions")
}
if addressOuts != nil {
// If there is any mempool add to the utxo set
FUNDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.Outpoints {
fundingTx, ok := addressOuts.TxnsStore[f.Hash]
if !ok {
apiLog.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if fundingTx.Confirmed() {
apiLog.Errorf("An outpoint's transaction is unexpectedly confirmed.")
continue
}
// TODO: Confirmed() not always return true for txs that have
// already been confirmed in a block. The mempool cache update
// process should correctly update these. Until we sort out why we
// need to do one more search on utxo and do not add if this is
// already in the list as a confirmed tx.
for _, utxo := range confirmedTxnOutputs {
if utxo.Vout == f.Index && utxo.TxnID == f.Hash.String() {
continue FUNDING_TX_DUPLICATE_CHECK
}
}
txnOutput := apitypes.AddressTxnOutput{
Address: address,
TxnID: fundingTx.Hash().String(),
Vout: f.Index,
ScriptPubKey: hex.EncodeToString(fundingTx.Tx.TxOut[f.Index].PkScript),
Amount: dcrutil.Amount(fundingTx.Tx.TxOut[f.Index].Value).ToCoin(),
Satoshis: fundingTx.Tx.TxOut[f.Index].Value,
Confirmations: 0,
BlockTime: fundingTx.MemPoolTime,
}
txnOutputs = append(txnOutputs, txnOutput)
}
}
txnOutputs = append(txnOutputs, confirmedTxnOutputs...)
// Search for items in mempool that spend utxo (matching hash and index)
// and remove those from the set
for _, f := range addressOuts.PrevOuts {
spendingTx, ok := addressOuts.TxnsStore[f.TxSpending]
if !ok {
apiLog.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if spendingTx.Confirmed() {
apiLog.Errorf("A transaction spending the outpoint of an unconfirmed transaction is unexpectedly confirmed.")
continue
}
for g, utxo := range txnOutputs {
if utxo.Vout == f.PreviousOutpoint.Index && utxo.TxnID == f.PreviousOutpoint.Hash.String() {
// Found a utxo that is unconfirmed spent. Remove from slice
txnOutputs = append(txnOutputs[:g], txnOutputs[g+1:]...)
}
}
}
}
// Final sort by timestamp desc if unconfirmed and by confirmations
// ascending if confirmed
sort.Slice(txnOutputs, func(i, j int) bool {
if txnOutputs[i].Confirmations == 0 && txnOutputs[j].Confirmations == 0 {
return txnOutputs[i].BlockTime > txnOutputs[j].BlockTime
}
return txnOutputs[i].Confirmations < txnOutputs[j].Confirmations
})
writeJSON(w, txnOutputs, c.getIndentQuery(r))
}
func (c *insightApiContext) getTransactions(w http.ResponseWriter, r *http.Request) {
hash := m.GetBlockHashCtx(r)
address := m.GetAddressCtx(r)
if hash == "" && address == "" {
writeInsightError(w, "Required query parameters (address or block) not present.")
return
}
if hash != "" {
blkTrans := c.BlockData.GetBlockVerboseByHash(hash, true)
if blkTrans == nil {
apiLog.Errorf("Unable to get block %s transactions", hash)
writeInsightError(w, fmt.Sprintf("Unable to get block %s transactions", hash))
return
}
txsOld := []*dcrjson.TxRawResult{}
txcount := len(blkTrans.RawTx) + len(blkTrans.RawSTx)
// Merge tx and stx together and limit result to 10 max
count := 0
for _, tx := range blkTrans.RawTx {
txsOld = append(txsOld, &tx)
count++
if count > 10 {
break
}
}
if count < 10 {
for _, tx := range blkTrans.RawSTx {
txsOld = append(txsOld, &tx)
count++
if count > 10 {
break
}
}
}
// Convert to Insight struct
txsNew, err := c.TxConverter(txsOld)
if err != nil {
apiLog.Error("Error Processing Transactions")
writeInsightError(w, "Error Processing Transactions")
return
}
blockTransactions := apitypes.InsightBlockAddrTxSummary{
PagesTotal: int64(txcount),
Txs: txsNew,
}
writeJSON(w, blockTransactions, c.getIndentQuery(r))
return
}
if address != "" {
// Validate Address
_, err := dcrutil.DecodeAddress(address)
if err != nil {
writeInsightError(w, fmt.Sprintf("Address is invalid (%s)", address))
return
}
addresses := []string{address}
rawTxs, recentTxs := c.BlockData.ChainDB.InsightPgGetAddressTransactions(addresses, int64(c.Status.Height-2))
addressOuts, _, err := c.MemPool.UnconfirmedTxnsForAddress(address)
UnconfirmedTxs := []string{}
if err != nil {
writeInsightError(w, fmt.Sprintf("Error gathering mempool transactions (%s)", err))
return
}
FUNDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.Outpoints {
// Confirm its not already in our recent transactions
for _, v := range recentTxs {
if v == f.Hash.String() {
continue FUNDING_TX_DUPLICATE_CHECK
}
}
UnconfirmedTxs = append(UnconfirmedTxs, f.Hash.String()) // Funding tx
recentTxs = append(recentTxs, f.Hash.String())
}
SPENDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.PrevOuts {
for _, v := range recentTxs {
if v == f.TxSpending.String() {
continue SPENDING_TX_DUPLICATE_CHECK
}
}
UnconfirmedTxs = append(UnconfirmedTxs, f.TxSpending.String()) // Spending tx
recentTxs = append(recentTxs, f.TxSpending.String())
}
// Merge unconfirmed with confirmed transactions
rawTxs = append(UnconfirmedTxs, rawTxs...)
txcount := len(rawTxs)
if txcount > 10 {
rawTxs = rawTxs[0:10]
}
txsOld := []*dcrjson.TxRawResult{}
for _, rawTx := range rawTxs {
txOld, err1 := c.BlockData.GetRawTransaction(rawTx)
if err1 != nil {
apiLog.Errorf("Unable to get transaction %s", rawTx)
writeInsightError(w, fmt.Sprintf("Error gathering transaction details (%s)", err1))
return
}
txsOld = append(txsOld, txOld)
}
// Convert to Insight struct
txsNew, err := c.TxConverter(txsOld)
if err != nil {
apiLog.Error("Error Processing Transactions")
writeInsightError(w, "Error Processing Transactions")
return
}
addrTransactions := apitypes.InsightBlockAddrTxSummary{
PagesTotal: int64(txcount),
Txs: txsNew,
}
writeJSON(w, addrTransactions, c.getIndentQuery(r))
}
}
func (c *insightApiContext) getAddressesTxn(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r) // Required
if address == "" {
writeInsightError(w, "Address cannot be empty")
return
}
noAsm := c.GetNoAsmCtx(r) // Optional
noScriptSig := c.GetNoScriptSigCtx(r) // Optional
noSpent := c.GetNoSpentCtx(r) // Optional
from := c.GetFromCtx(r) // Optional
to, ok := c.GetToCtx(r) // Optional
if !ok {
to = from + 10
}
// Allow Addresses to be single or multiple separated by a comma.
addresses := strings.Split(address, ",")
// Initialize Output Structure
addressOutput := new(apitypes.InsightMultiAddrsTxOutput)
UnconfirmedTxs := []string{}
rawTxs, recentTxs := c.BlockData.ChainDB.InsightPgGetAddressTransactions(addresses, int64(c.Status.Height-2))
// Confirm all addresses are valid and pull unconfirmed transactions for all addresses
for _, addr := range addresses {
address, err := dcrutil.DecodeAddress(addr)
if err != nil {
writeInsightError(w, fmt.Sprintf("Address is invalid (%s)", addr))
return
}
addressOuts, _, err := c.MemPool.UnconfirmedTxnsForAddress(address.String())
if err != nil {
writeInsightError(w, fmt.Sprintf("Error gathering mempool transactions (%s)", err))
return
}
FUNDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.Outpoints {
// Confirm its not already in our recent transactions
for _, v := range recentTxs {
if v == f.Hash.String() {
continue FUNDING_TX_DUPLICATE_CHECK
}
}
UnconfirmedTxs = append(UnconfirmedTxs, f.Hash.String()) // Funding tx
recentTxs = append(recentTxs, f.Hash.String())
}
SPENDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.PrevOuts {
for _, v := range recentTxs {
if v == f.TxSpending.String() {
continue SPENDING_TX_DUPLICATE_CHECK
}
}
UnconfirmedTxs = append(UnconfirmedTxs, f.TxSpending.String()) // Spending tx
recentTxs = append(recentTxs, f.TxSpending.String())
}
}
// Merge unconfirmed with confirmed transactions
rawTxs = append(UnconfirmedTxs, rawTxs...)
txcount := len(rawTxs)
addressOutput.TotalItems = int64(txcount)
if txcount > 0 {
if int(from) > txcount {
from = int64(txcount)
}
if int(from) < 0 {
from = 0
}
if int(to) > txcount {
to = int64(txcount)
}
if int(to) < 0 {
to = 0
}
if from > to {
to = from
}
if (to - from) > 50 {
writeInsightError(w, fmt.Sprintf("\"from\" (%d) and \"to\" (%d) range should be less than or equal to 50", from, to))
return
}
// Final Slice Extraction
rawTxs = rawTxs[from:to]
}
addressOutput.From = int(from)
addressOutput.To = int(to)
txsOld := []*dcrjson.TxRawResult{}
for _, rawTx := range rawTxs {
txOld, err := c.BlockData.GetRawTransaction(rawTx)
if err != nil {
apiLog.Errorf("Unable to get transaction %s", rawTx)
writeInsightError(w, fmt.Sprintf("Error gathering transaction details (%s)", err))
return
}
txsOld = append(txsOld, txOld)
}
// Convert to Insight API struct
txsNew, err := c.DcrToInsightTxns(txsOld, noAsm, noScriptSig, noSpent)
if err != nil {
apiLog.Error("Unable to process transactions")
writeInsightError(w, fmt.Sprintf("Unable to convert transactions (%s)", err))
return
}
addressOutput.Items = append(addressOutput.Items, txsNew...)
if addressOutput.Items == nil {
// Make sure we pass an empty array not null to json response if no Tx
addressOutput.Items = make([]apitypes.InsightTx, 0)
}
writeJSON(w, addressOutput, c.getIndentQuery(r))
}
func (c *insightApiContext) getAddressBalance(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r)
if address == "" {
http.Error(w, http.StatusText(422), 422)
return
}
addressInfo := c.BlockData.ChainDB.GetAddressBalance(address, 20, 0)
if addressInfo == nil {
http.Error(w, http.StatusText(422), 422)
return
}
writeJSON(w, addressInfo.TotalUnspent, c.getIndentQuery(r))
}
func (c *insightApiContext) getAddressTotalReceived(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r)
if address == "" {
http.Error(w, http.StatusText(422), 422)
return
}
addressInfo := c.BlockData.ChainDB.GetAddressBalance(address, 20, 0)
if addressInfo == nil {
http.Error(w, http.StatusText(422), 422)
return
}
totalReceived := addressInfo.TotalSpent + addressInfo.TotalUnspent
writeText(w, strconv.Itoa(int(totalReceived)))
}
func (c *insightApiContext) getAddressUnconfirmedBalance(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r)
if address == "" {
http.Error(w, http.StatusText(422), 422)
return
}
addressInfo := c.BlockData.ChainDB.GetAddressBalance(address, 20, 0)
if addressInfo == nil {
http.Error(w, http.StatusText(422), 422)
return
}
writeText(w, string(addressInfo.TotalUnspent))
}
func (c *insightApiContext) getAddressTotalSent(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r)
if address == "" {
http.Error(w, http.StatusText(422), 422)
return
}
addressInfo := c.BlockData.ChainDB.GetAddressBalance(address, 20, 0)
if addressInfo == nil {
http.Error(w, http.StatusText(422), 422)
return
}
writeText(w, strconv.Itoa(int(addressInfo.TotalSpent)))
}
func (c *insightApiContext) getStatusInfo(w http.ResponseWriter, r *http.Request) {
statusInfo := m.GetStatusInfoCtx(r)
// best block idx is also embedded through the middleware. We could use
// this value or the other best blocks as done below. Which one is best?
// idx := m.GetBlockIndexCtx(r)
infoResult, err := c.nodeClient.GetInfo()
if err != nil {
apiLog.Error("Error getting status")
writeInsightError(w, fmt.Sprintf("Error getting status (%s)", err))
return
}
switch statusInfo {
case "getDifficulty":
info := struct {
Difficulty float64 `json:"difficulty"`
}{
infoResult.Difficulty,
}
writeJSON(w, info, c.getIndentQuery(r))
case "getBestBlockHash":
blockhash, err := c.nodeClient.GetBlockHash(int64(infoResult.Blocks))
if err != nil {
apiLog.Errorf("Error getting block hash %d (%s)", infoResult.Blocks, err)
writeInsightError(w, fmt.Sprintf("Error getting block hash %d (%s)", infoResult.Blocks, err))
return
}
info := struct {
BestBlockHash string `json:"bestblockhash"`
}{
blockhash.String(),
}
writeJSON(w, info, c.getIndentQuery(r))
case "getLastBlockHash":
blockhashtip, err := c.nodeClient.GetBlockHash(int64(infoResult.Blocks))
if err != nil {
apiLog.Errorf("Error getting block hash %d (%s)", infoResult.Blocks, err)
writeInsightError(w, fmt.Sprintf("Error getting block hash %d (%s)", infoResult.Blocks, err))
return
}
lastblockhash, err := c.nodeClient.GetBlockHash(int64(c.Status.Height))
if err != nil {
apiLog.Errorf("Error getting block hash %d (%s)", c.Status.Height, err)
writeInsightError(w, fmt.Sprintf("Error getting block hash %d (%s)", c.Status.Height, err))
return
}
info := struct {
SyncTipHash string `json:"syncTipHash"`
LastBlockHash string `json:"lastblockhash"`
}{
blockhashtip.String(),
lastblockhash.String(),
}
writeJSON(w, info, c.getIndentQuery(r))
default:
info := struct {
Version int32 `json:"version"`
Protocolversion int32 `json:"protocolversion"`
Blocks int32 `json:"blocks"`
NodeTimeoffset int64 `json:"timeoffset"`
NodeConnections int32 `json:"connections"`
Proxy string `json:"proxy"`
Difficulty float64 `json:"difficulty"`
Testnet bool `json:"testnet"`
Relayfee float64 `json:"relayfee"`
Errors string `json:"errors"`
}{
infoResult.Version,
infoResult.ProtocolVersion,
infoResult.Blocks,
infoResult.TimeOffset,
infoResult.Connections,
infoResult.Proxy,
infoResult.Difficulty,
infoResult.TestNet,
infoResult.RelayFee,
infoResult.Errors,
}
writeJSON(w, info, c.getIndentQuery(r))
}
}
func (c *insightApiContext) getBlockSummaryByTime(w http.ResponseWriter, r *http.Request) {
blockDate := m.GetBlockDateCtx(r)
limit := c.GetLimitCtx(r)
summaryOutput := apitypes.InsightBlocksSummaryResult{}
layout := "2006-01-02 15:04:05"
blockDateToday := time.Now().UTC().Format("2006-01-02")
if blockDate == "" {
blockDate = blockDateToday
}
if blockDateToday == blockDate {
summaryOutput.Pagination.IsToday = true
}
minDate, err := time.Parse(layout, blockDate+" 00:00:00")
if err != nil {
writeInsightError(w, fmt.Sprintf("Unable to retrieve block summary using time %s: %v", blockDate, err))
return
}
maxDate, err := time.Parse(layout, blockDate+" 23:59:59")
if err != nil {
writeInsightError(w, fmt.Sprintf("Unable to retrieve block summary using time %s: %v", blockDate, err))
return
}
summaryOutput.Pagination.Next = minDate.AddDate(0, 0, 1).Format("2006-01-02")
summaryOutput.Pagination.Prev = minDate.AddDate(0, 0, -1).Format("2006-01-02")
summaryOutput.Pagination.Current = blockDate
minTime, maxTime := minDate.Unix(), maxDate.Unix()
summaryOutput.Pagination.CurrentTs = maxTime
summaryOutput.Pagination.MoreTs = maxTime
blockSummary := c.BlockData.ChainDB.GetBlockSummaryTimeRange(minTime, maxTime, 0)
outputBlockSummary := []dbtypes.BlockDataBasic{}
// Generate the pagenation parameters more and moreTs and limit the result
if limit > 0 {
for i, block := range blockSummary {
if i >= limit {
summaryOutput.Pagination.More = true
break
}
outputBlockSummary = append(outputBlockSummary, block)
if block.Time < summaryOutput.Pagination.MoreTs {
summaryOutput.Pagination.MoreTs = block.Time
}
}
summaryOutput.Blocks = outputBlockSummary
} else {
summaryOutput.Blocks = blockSummary
summaryOutput.Pagination.More = false
summaryOutput.Pagination.MoreTs = minTime
}
summaryOutput.Length = len(summaryOutput.Blocks)
writeJSON(w, summaryOutput, c.getIndentQuery(r))
}
func (c *insightApiContext) getAddressInfo(w http.ResponseWriter, r *http.Request) {
address := m.GetAddressCtx(r)
command, isCmd := c.GetAddressCommandCtx(r)
_, err := dcrutil.DecodeAddress(address)
if err != nil {
writeInsightError(w, "Invalid Address")
return
}
noTxList := c.GetNoTxListCtx(r)
from := c.GetFromCtx(r)
to, ok := c.GetToCtx(r)
if !ok || to <= from {
to = from + 1000
}
// Get Confirmed Balances
var unconfirmedBalanceSat int64
_, _, totalSpent, totalUnspent, err := c.BlockData.ChainDB.RetrieveAddressSpentUnspent(address)
if err != nil {
return
}
if isCmd {
switch command {
case "balance":
writeJSON(w, totalUnspent, c.getIndentQuery(r))
return
case "totalReceived":
writeJSON(w, totalSpent+totalUnspent, c.getIndentQuery(r))
return
case "totalSent":
writeJSON(w, totalSpent, c.getIndentQuery(r))
return
}
}
addresses := []string{address}
// Get Confirmed Transactions
rawTxs, recentTxs := c.BlockData.ChainDB.InsightPgGetAddressTransactions(addresses, int64(c.Status.Height-2))
confirmedTxCount := len(rawTxs)
// Get Unconfirmed Transactions
unconfirmedTxs := []string{}
addressOuts, _, err := c.MemPool.UnconfirmedTxnsForAddress(address)
if err != nil {
apiLog.Errorf("Error in getting unconfirmed transactions")
}
if addressOuts != nil {
FUNDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.Outpoints {
// Confirm its not already in our recent transactions
for _, v := range recentTxs {
if v == f.Hash.String() {
continue FUNDING_TX_DUPLICATE_CHECK
}
}
fundingTx, ok := addressOuts.TxnsStore[f.Hash]
if !ok {
apiLog.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if fundingTx.Confirmed() {
apiLog.Errorf("An outpoint's transaction is unexpectedly confirmed.")
continue
}
unconfirmedBalanceSat += fundingTx.Tx.TxOut[f.Index].Value
unconfirmedTxs = append(unconfirmedTxs, f.Hash.String()) // Funding tx
recentTxs = append(recentTxs, f.Hash.String())
}
SPENDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.PrevOuts {
for _, v := range recentTxs {
if v == f.TxSpending.String() {
continue SPENDING_TX_DUPLICATE_CHECK
}
}
spendingTx, ok := addressOuts.TxnsStore[f.TxSpending]
if !ok {
apiLog.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if spendingTx.Confirmed() {
apiLog.Errorf("A transaction spending the outpoint of an unconfirmed transaction is unexpectedly confirmed.")
continue
}
// Sent total sats has to be a lookup of the vout:i prevout value
// because vin:i valuein is not reliable from dcrd at present
prevhash := spendingTx.Tx.TxIn[f.InputIndex].PreviousOutPoint.Hash
previndex := spendingTx.Tx.TxIn[f.InputIndex].PreviousOutPoint.Index
valuein := addressOuts.TxnsStore[prevhash].Tx.TxOut[previndex].Value
unconfirmedBalanceSat -= valuein
unconfirmedTxs = append(unconfirmedTxs, f.TxSpending.String()) // Spending tx
recentTxs = append(recentTxs, f.TxSpending.String())
}
}
if isCmd {
switch command {
case "unconfirmedBalance":
writeJSON(w, unconfirmedBalanceSat, c.getIndentQuery(r))
return
}
}
// Merge Unconfirmed with Confirmed transactions
rawTxs = append(unconfirmedTxs, rawTxs...)
// Final Slice Extraction
txcount := len(rawTxs)
if txcount > 0 {
if int(from) > txcount {
from = int64(txcount)
}
if int(from) < 0 {
from = 0
}
if int(to) > txcount {
to = int64(txcount)
}
if int(to) < 0 {
to = 0
}
if from > to {
to = from
}
if (to - from) > 1000 {
writeInsightError(w, fmt.Sprintf("\"from\" (%d) and \"to\" (%d) range should be less than or equal to 1000", from, to))
return
}
rawTxs = rawTxs[from:to]
}
addressInfo := apitypes.InsightAddressInfo{
Address: address,
TotalReceivedSat: (totalSpent + totalUnspent),
TotalSentSat: totalSpent,
BalanceSat: totalUnspent,
TotalReceived: dcrutil.Amount(totalSpent + totalUnspent).ToCoin(),
TotalSent: dcrutil.Amount(totalSpent).ToCoin(),
Balance: dcrutil.Amount(totalUnspent).ToCoin(),
TxAppearances: int64(confirmedTxCount),