-
Notifications
You must be signed in to change notification settings - Fork 128
/
explorerroutes.go
739 lines (676 loc) · 25.1 KB
/
explorerroutes.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
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package explorer
import (
"database/sql"
"io"
"math"
"net/http"
"sort"
"strconv"
"strings"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrdata/db/dbtypes"
"github.com/decred/dcrdata/txhelpers"
humanize "github.com/dustin/go-humanize"
)
// netName returns the name used when referring to a decred network.
func netName(chainParams *chaincfg.Params) string {
if strings.HasPrefix(strings.ToLower(chainParams.Name), "testnet") {
return "Testnet"
}
return strings.Title(chainParams.Name)
}
// Home is the page handler for the "/" path
func (exp *explorerUI) Home(w http.ResponseWriter, r *http.Request) {
height := exp.blockData.GetHeight()
blocks := exp.blockData.GetExplorerBlocks(height, height-5)
exp.NewBlockDataMtx.Lock()
exp.MempoolData.RLock()
str, err := exp.templates.execTemplateToString("home", struct {
Info *HomeInfo
Mempool *MempoolInfo
Blocks []*BlockBasic
Version string
NetName string
}{
exp.ExtraInfo,
exp.MempoolData,
blocks,
exp.Version,
exp.NetName,
})
exp.NewBlockDataMtx.Unlock()
exp.MempoolData.RUnlock()
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// Blocks is the page handler for the "/blocks" path
func (exp *explorerUI) Blocks(w http.ResponseWriter, r *http.Request) {
idx := exp.blockData.GetHeight()
height, err := strconv.Atoi(r.URL.Query().Get("height"))
if err != nil || height > idx {
height = idx
}
rows, err := strconv.Atoi(r.URL.Query().Get("rows"))
if err != nil || rows > maxExplorerRows || rows < minExplorerRows {
rows = minExplorerRows
}
oldestBlock := height - rows + 1
if oldestBlock < 0 {
height = rows - 1
}
summaries := exp.blockData.GetExplorerBlocks(height, height-rows)
if summaries == nil {
log.Errorf("Unable to get blocks: height=%d&rows=%d", height, rows)
exp.ErrorPage(w, "Something went wrong...", "could not find those blocks", true)
return
}
str, err := exp.templates.execTemplateToString("explorer", struct {
Data []*BlockBasic
BestBlock int
Rows int
Version string
NetName string
}{
summaries,
idx,
rows,
exp.Version,
exp.NetName,
})
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// Block is the page handler for the "/block" path
func (exp *explorerUI) Block(w http.ResponseWriter, r *http.Request) {
hash := getBlockHashCtx(r)
data := exp.blockData.GetExplorerBlock(hash)
if data == nil {
log.Errorf("Unable to get block %s", hash)
exp.ErrorPage(w, "Something went wrong...", "could not find that block", true)
return
}
// Checking if there exists any regular non-Coinbase transactions in the block.
var count int
data.TxAvailable = true
for _, i := range data.Tx {
if i.Coinbase {
count++
}
}
if count == len(data.Tx) {
data.TxAvailable = false
}
if !exp.liteMode {
var err error
data.Misses, err = exp.explorerSource.BlockMissedVotes(hash)
if err != nil && err != sql.ErrNoRows {
log.Warnf("Unable to retrieve missed votes for block %s: %v", hash, err)
}
}
pageData := struct {
Data *BlockInfo
ConfirmHeight int64
Version string
NetName string
}{
data,
exp.NewBlockData.Height - data.Confirmations,
exp.Version,
exp.NetName,
}
str, err := exp.templates.execTemplateToString("block", pageData)
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Turbolinks-Location", r.URL.RequestURI())
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// Mempool is the page handler for the "/mempool" path
func (exp *explorerUI) Mempool(w http.ResponseWriter, r *http.Request) {
exp.MempoolData.RLock()
str, err := exp.templates.execTemplateToString("mempool", struct {
Mempool *MempoolInfo
Version string
NetName string
}{
exp.MempoolData,
exp.Version,
exp.NetName,
})
exp.MempoolData.RUnlock()
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// TxPage is the page handler for the "/tx" path
func (exp *explorerUI) TxPage(w http.ResponseWriter, r *http.Request) {
// attempt to get tx hash string from URL path
hash, ok := r.Context().Value(ctxTxHash).(string)
if !ok {
log.Trace("txid not set")
exp.ErrorPage(w, "Something went wrong...", "there was no transaction requested", true)
return
}
tx := exp.blockData.GetExplorerTx(hash)
if tx == nil {
log.Errorf("Unable to get transaction %s", hash)
exp.ErrorPage(w, "Something went wrong...", "could not find that transaction", true)
return
}
// Set ticket-related parameters for both full and lite mode
if tx.IsTicket() {
blocksLive := tx.Confirmations - int64(exp.ChainParams.TicketMaturity)
tx.TicketInfo.TicketPoolSize = int64(exp.ChainParams.TicketPoolSize) *
int64(exp.ChainParams.TicketsPerBlock)
tx.TicketInfo.TicketExpiry = int64(exp.ChainParams.TicketExpiry)
expirationInDays := (exp.ChainParams.TargetTimePerBlock.Hours() *
float64(exp.ChainParams.TicketExpiry)) / 24
maturityInHours := (exp.ChainParams.TargetTimePerBlock.Hours() *
float64(tx.TicketInfo.TicketMaturity))
tx.TicketInfo.TimeTillMaturity = ((float64(exp.ChainParams.TicketMaturity) -
float64(tx.Confirmations)) / float64(exp.ChainParams.TicketMaturity)) * maturityInHours
ticketExpiryBlocksLeft := int64(exp.ChainParams.TicketExpiry) - blocksLive
tx.TicketInfo.TicketExpiryDaysLeft = (float64(ticketExpiryBlocksLeft) /
float64(exp.ChainParams.TicketExpiry)) * expirationInDays
}
if !exp.liteMode {
// For any coinbase transactions look up the total block fees to include as part of the inputs
if tx.Type == "Coinbase" {
data := exp.blockData.GetExplorerBlock(tx.BlockHash)
if data == nil {
log.Errorf("Unable to get block %s", tx.BlockHash)
} else {
tx.BlockMiningFee = int64(data.MiningFee)
}
}
// For each output of this transaction, look up any spending transactions,
// and the index of the spending transaction input.
spendingTxHashes, spendingTxVinInds, voutInds, err := exp.explorerSource.SpendingTransactions(hash)
if err != nil {
log.Errorf("Unable to retrieve spending transactions for %s: %v", hash, err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
for i, vout := range voutInds {
if int(vout) >= len(tx.SpendingTxns) {
log.Errorf("Invalid spending transaction data (%s:%d)", hash, vout)
continue
}
tx.SpendingTxns[vout] = TxInID{
Hash: spendingTxHashes[i],
Index: spendingTxVinInds[i],
}
}
if tx.IsTicket() {
spendStatus, poolStatus, err := exp.explorerSource.PoolStatusForTicket(hash)
if err != nil {
log.Errorf("Unable to retrieve ticket spend and pool status for %s: %v", hash, err)
} else {
if tx.Mature == "False" {
tx.TicketInfo.PoolStatus = "immature"
} else {
tx.TicketInfo.PoolStatus = poolStatus.String()
}
tx.TicketInfo.SpendStatus = spendStatus.String()
// Ticket luck and probability of voting
blocksLive := tx.Confirmations - int64(exp.ChainParams.TicketMaturity)
if tx.TicketInfo.SpendStatus == "Voted" {
// Blocks from eligible until voted (actual luck)
tx.TicketInfo.TicketLiveBlocks = exp.blockData.TxHeight(tx.SpendingTxns[0].Hash) -
tx.BlockHeight - int64(exp.ChainParams.TicketMaturity) - 1
} else if tx.Confirmations >= int64(exp.ChainParams.TicketExpiry+
uint32(exp.ChainParams.TicketMaturity)) { // Expired
// Blocks ticket was active before expiring (actual no luck)
tx.TicketInfo.TicketLiveBlocks = int64(exp.ChainParams.TicketExpiry)
} else { // Active
// Blocks ticket has been active and eligible to vote
tx.TicketInfo.TicketLiveBlocks = blocksLive
}
tx.TicketInfo.BestLuck = tx.TicketInfo.TicketExpiry / int64(exp.ChainParams.TicketPoolSize)
tx.TicketInfo.AvgLuck = tx.TicketInfo.BestLuck - 1
if tx.TicketInfo.TicketLiveBlocks == int64(exp.ChainParams.TicketExpiry) {
tx.TicketInfo.VoteLuck = 0
} else {
tx.TicketInfo.VoteLuck = float64(tx.TicketInfo.BestLuck) -
(float64(tx.TicketInfo.TicketLiveBlocks) / float64(exp.ChainParams.TicketPoolSize))
}
if tx.TicketInfo.VoteLuck >= float64(tx.TicketInfo.BestLuck-(1/int64(exp.ChainParams.TicketPoolSize))) {
tx.TicketInfo.LuckStatus = "Perfection"
} else if tx.TicketInfo.VoteLuck > (float64(tx.TicketInfo.BestLuck) - 0.25) {
tx.TicketInfo.LuckStatus = "Very Lucky!"
} else if tx.TicketInfo.VoteLuck > (float64(tx.TicketInfo.BestLuck) - 0.75) {
tx.TicketInfo.LuckStatus = "Good Luck"
} else if tx.TicketInfo.VoteLuck > (float64(tx.TicketInfo.BestLuck) - 1.25) {
tx.TicketInfo.LuckStatus = "Normal"
} else if tx.TicketInfo.VoteLuck > (float64(tx.TicketInfo.BestLuck) * 0.50) {
tx.TicketInfo.LuckStatus = "Bad Luck"
} else if tx.TicketInfo.VoteLuck > 0 {
tx.TicketInfo.LuckStatus = "Horrible Luck!"
} else if tx.TicketInfo.VoteLuck == 0 {
tx.TicketInfo.LuckStatus = "No Luck"
}
// Chance for a ticket to NOT be voted in a given time frame:
// C = (1 - P)^N
// Where: P is the probability of a vote in one block. (votes
// per block / current ticket pool size)
// N is the number of blocks before ticket expiry. (ticket
// expiry in blocks - (number of blocks since ticket purchase -
// ticket maturity))
// C is the probability (chance)
pVote := float64(exp.ChainParams.TicketsPerBlock) / float64(exp.ExtraInfo.PoolInfo.Size)
tx.TicketInfo.Probability = 100 * (math.Pow(1-pVote,
float64(exp.ChainParams.TicketExpiry)-float64(blocksLive)))
}
}
}
pageData := struct {
Data *TxInfo
ConfirmHeight int64
Version string
NetName string
}{
tx,
exp.NewBlockData.Height - tx.Confirmations,
exp.Version,
exp.NetName,
}
str, err := exp.templates.execTemplateToString("tx", pageData)
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Turbolinks-Location", r.URL.RequestURI())
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// AddressPage is the page handler for the "/address" path
func (exp *explorerUI) AddressPage(w http.ResponseWriter, r *http.Request) {
// AddressPageData is the data structure passed to the HTML template
type AddressPageData struct {
Data *AddressInfo
ConfirmHeight []int64
Version string
NetName string
}
// Get the address URL parameter, which should be set in the request context
// by the addressPathCtx middleware.
address, ok := r.Context().Value(ctxAddress).(string)
if !ok {
log.Trace("address not set")
exp.ErrorPage(w, "Something went wrong...", "there seems to not be an address in this request", true)
return
}
// Number of outputs for the address to query the database for. The URL
// query parameter "n" is used to specify the limit (e.g. "?n=20").
limitN, err := strconv.ParseInt(r.URL.Query().Get("n"), 10, 64)
if err != nil || limitN < 0 {
limitN = defaultAddressRows
} else if limitN > MaxAddressRows {
log.Warnf("addressPage: requested up to %d address rows, "+
"limiting to %d", limitN, MaxAddressRows)
limitN = MaxAddressRows
}
// Number of outputs to skip (OFFSET in database query). For UX reasons, the
// "start" URL query parameter is used.
offsetAddrOuts, err := strconv.ParseInt(r.URL.Query().Get("start"), 10, 64)
if err != nil || offsetAddrOuts < 0 {
offsetAddrOuts = 0
}
// Transaction types to show.
txntype := r.URL.Query().Get("txntype")
if txntype == "" {
txntype = "all"
}
txnType := dbtypes.AddrTxnTypeFromStr(txntype)
if txnType == dbtypes.AddrTxnUnknown {
exp.ErrorPage(w, "Something went wrong...", "unknown txntype query value", false)
return
}
log.Debugf("Showing transaction types: %s (%d)", txntype, txnType)
// Retrieve address information from the DB and/or RPC
var addrData *AddressInfo
if exp.liteMode {
addrData = exp.blockData.GetExplorerAddress(address, limitN, offsetAddrOuts)
if addrData == nil {
log.Errorf("Unable to get address %s", address)
exp.ErrorPage(w, "Something went wrong...", "could not find that address", true)
return
}
} else {
// Get addresses table rows for the address
addrHist, balance, errH := exp.explorerSource.AddressHistory(
address, limitN, offsetAddrOuts, txnType)
if errH == nil {
// Generate AddressInfo skeleton from the address table rows
addrData = ReduceAddressHistory(addrHist)
if addrData == nil {
// Empty history is not expected for credit txnType with any txns.
if txnType != dbtypes.AddrTxnDebit && (balance.NumSpent+balance.NumUnspent) > 0 {
log.Debugf("empty address history (%s): n=%d&start=%d", address, limitN, offsetAddrOuts)
exp.ErrorPage(w, "Something went wrong...", "that address has no history", true)
return
}
// No mined transactions
addrData = new(AddressInfo)
addrData.Address = address
}
addrData.Fullmode = true
// Balances and txn counts (partial unless in full mode)
addrData.Balance = balance
addrData.KnownTransactions = (balance.NumSpent * 2) + balance.NumUnspent
addrData.KnownFundingTxns = balance.NumSpent + balance.NumUnspent
addrData.KnownSpendingTxns = balance.NumSpent
// Transactions to fetch with FillAddressTransactions. This should be a
// noop if ReduceAddressHistory is working right.
switch txnType {
case dbtypes.AddrTxnAll:
case dbtypes.AddrTxnCredit:
addrData.Transactions = addrData.TxnsFunding
case dbtypes.AddrTxnDebit:
addrData.Transactions = addrData.TxnsSpending
default:
log.Warnf("Unknown address transaction type: %v", txnType)
}
// Transactions on current page
addrData.NumTransactions = int64(len(addrData.Transactions))
if addrData.NumTransactions > limitN {
addrData.NumTransactions = limitN
}
// Query database for transaction details
err = exp.explorerSource.FillAddressTransactions(addrData)
if err != nil {
log.Errorf("Unable to fill address %s transactions: %v", address, err)
exp.ErrorPage(w, "Something went wrong...", "could not find transactions for that address", false)
return
}
} else {
// We do not have any confirmed transactions. Prep to display ONLY
// unconfirmed transactions (or none at all)
addrData = new(AddressInfo)
addrData.Address = address
addrData.Fullmode = true
addrData.Balance = &AddressBalance{}
}
// Check for unconfirmed transactions
addressOuts, numUnconfirmed, err := exp.blockData.UnconfirmedTxnsForAddress(address)
if err != nil {
log.Warnf("UnconfirmedTxnsForAddress failed for address %s: %v", address, err)
}
addrData.NumUnconfirmed = numUnconfirmed
if addrData.UnconfirmedTxns == nil {
addrData.UnconfirmedTxns = new(AddressTransactions)
}
// Funding transactions (unconfirmed)
var received, sent, numReceived, numSent int64
FUNDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.Outpoints {
//Mempool transactions stick around for 2 blocks. The first block
//incorporates the transaction and mines it. The second block
//validates it by the stake. However, transactions move into our
//database as soon as they are mined and thus we need to be careful
//to not include those transactions in our list.
for _, b := range addrData.Transactions {
if f.Hash.String() == b.TxID && f.Index == b.InOutID {
continue FUNDING_TX_DUPLICATE_CHECK
}
}
fundingTx, ok := addressOuts.TxnsStore[f.Hash]
if !ok {
log.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if fundingTx.Confirmed() {
log.Errorf("An outpoint's transaction is unexpectedly confirmed.")
continue
}
if txnType == dbtypes.AddrTxnAll || txnType == dbtypes.AddrTxnCredit {
addrTx := &AddressTx{
TxID: fundingTx.Hash().String(),
InOutID: f.Index,
Time: fundingTx.MemPoolTime,
FormattedSize: humanize.Bytes(uint64(fundingTx.Tx.SerializeSize())),
Total: txhelpers.TotalOutFromMsgTx(fundingTx.Tx).ToCoin(),
ReceivedTotal: dcrutil.Amount(fundingTx.Tx.TxOut[f.Index].Value).ToCoin(),
}
addrData.Transactions = append(addrData.Transactions, addrTx)
}
received += fundingTx.Tx.TxOut[f.Index].Value
numReceived++
}
// Spending transactions (unconfirmed)
SPENDING_TX_DUPLICATE_CHECK:
for _, f := range addressOuts.PrevOuts {
//Mempool transactions stick around for 2 blocks. The first block
//incorporates the transaction and mines it. The second block
//validates it by the stake. However, transactions move into our
//database as soon as they are mined and thus we need to be careful
//to not include those transactions in our list.
for _, b := range addrData.Transactions {
if f.TxSpending.String() == b.TxID && f.InputIndex == int(b.InOutID) {
continue SPENDING_TX_DUPLICATE_CHECK
}
}
spendingTx, ok := addressOuts.TxnsStore[f.TxSpending]
if !ok {
log.Errorf("An outpoint's transaction is not available in TxnStore.")
continue
}
if spendingTx.Confirmed() {
log.Errorf("An outpoint's 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
if txnType == dbtypes.AddrTxnAll || txnType == dbtypes.AddrTxnDebit {
addrTx := &AddressTx{
TxID: spendingTx.Hash().String(),
InOutID: uint32(f.InputIndex),
Time: spendingTx.MemPoolTime,
FormattedSize: humanize.Bytes(uint64(spendingTx.Tx.SerializeSize())),
Total: txhelpers.TotalOutFromMsgTx(spendingTx.Tx).ToCoin(),
SentTotal: dcrutil.Amount(valuein).ToCoin(),
}
addrData.Transactions = append(addrData.Transactions, addrTx)
}
sent += valuein
numSent++
}
addrData.Balance.NumSpent += numSent
addrData.Balance.NumUnspent += (numReceived - numSent)
addrData.Balance.TotalSpent += sent
addrData.Balance.TotalUnspent += (received - sent)
}
// Set page parameters
addrData.Path = r.URL.Path
addrData.Limit, addrData.Offset = limitN, offsetAddrOuts
addrData.TxnType = txnType.String()
confirmHeights := make([]int64, len(addrData.Transactions))
for i, v := range addrData.Transactions {
confirmHeights[i] = exp.NewBlockData.Height - int64(v.Confirmations)
}
sort.Slice(addrData.Transactions, func(i, j int) bool {
if addrData.Transactions[i].Time == addrData.Transactions[j].Time {
return addrData.Transactions[i].InOutID > addrData.Transactions[j].InOutID
}
return addrData.Transactions[i].Time > addrData.Transactions[j].Time
})
// addresscount := len(addressRows)
// if addresscount > 0 {
// calcoffset := int(math.Min(float64(addresscount), float64(offset)))
// calcN := int(math.Min(float64(offset+N), float64(addresscount)))
// log.Infof("Slicing result set which is %d addresses long to offset: %d and N: %d", addresscount, calcoffset, calcN)
// addressRows = addressRows[calcoffset:calcN]
// }
pageData := AddressPageData{
Data: addrData,
ConfirmHeight: confirmHeights,
Version: exp.Version,
NetName: exp.NetName,
}
str, err := exp.templates.execTemplateToString("address", pageData)
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Turbolinks-Location", r.URL.RequestURI())
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// DecodeTxPage handles the "decode/broadcast transaction" page. The actual
// decoding or broadcasting is handled by the websocket hub.
func (exp *explorerUI) DecodeTxPage(w http.ResponseWriter, r *http.Request) {
str, err := exp.templates.execTemplateToString("rawtx", struct {
Version string
NetName string
}{
exp.Version,
exp.NetName,
})
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing, that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
// Search implements a primitive search algorithm by checking if the value in
// question is a block index, block hash, address hash or transaction hash and
// redirects to the appropriate page or displays an error
func (exp *explorerUI) Search(w http.ResponseWriter, r *http.Request) {
searchStr := r.URL.Query().Get("search")
if searchStr == "" {
exp.ErrorPage(w, "search failed", "Nothing was searched for", true)
return
}
// Attempt to get a block hash by calling GetBlockHash to see if the value
// is a block index and then redirect to the block page if it is
idx, err := strconv.ParseInt(searchStr, 10, 0)
if err == nil {
_, err = exp.blockData.GetBlockHash(idx)
if err == nil {
http.Redirect(w, r, "/block/"+searchStr, http.StatusPermanentRedirect)
return
}
exp.ErrorPage(w, "search failed", "Block "+searchStr+" has not yet been mined", true)
return
}
// Call GetExplorerAddress to see if the value is an address hash and
// then redirect to the address page if it is
address := exp.blockData.GetExplorerAddress(searchStr, 1, 0)
if address != nil {
http.Redirect(w, r, "/address/"+searchStr, http.StatusPermanentRedirect)
return
}
// Check if the value is a valid hash
if _, err = chainhash.NewHashFromStr(searchStr); err != nil {
exp.ErrorPage(w, "search failed", "Couldn't find any address "+searchStr, true)
return
}
// Attempt to get a block index by calling GetBlockHeight to see if the
// value is a block hash and then redirect to the block page if it is
_, err = exp.blockData.GetBlockHeight(searchStr)
if err == nil {
http.Redirect(w, r, "/block/"+searchStr, http.StatusPermanentRedirect)
return
}
// Call GetExplorerTx to see if the value is a transaction hash and then
// redirect to the tx page if it is
tx := exp.blockData.GetExplorerTx(searchStr)
if tx != nil {
http.Redirect(w, r, "/tx/"+searchStr, http.StatusPermanentRedirect)
return
}
exp.ErrorPage(w, "search failed", "Could not find any transaction or block "+searchStr, true)
}
// ErrorPage provides a way to show error on the pages without redirecting
func (exp *explorerUI) ErrorPage(w http.ResponseWriter, code string, message string, notFound bool) {
str, err := exp.templates.execTemplateToString("error", struct {
ErrorCode string
ErrorString string
Version string
NetName string
}{
code,
message,
exp.Version,
exp.NetName,
})
if err != nil {
log.Errorf("Template execute failure: %v", err)
str = "Something went very wrong if you can see this, try refreshing"
}
w.Header().Set("Content-Type", "text/html")
if notFound {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
io.WriteString(w, str)
}
// NotFound wraps ErrorPage to display a 404 page
func (exp *explorerUI) NotFound(w http.ResponseWriter, r *http.Request) {
exp.ErrorPage(w, "Not found", "Cannot find page: "+r.URL.Path, true)
}
// ParametersPage is the page handler for the "/parameters" path
func (exp *explorerUI) ParametersPage(w http.ResponseWriter, r *http.Request) {
cp := exp.ChainParams
addrPrefix := AddressPrefixes(cp)
actualTicketPoolSize := int64(cp.TicketPoolSize * cp.TicketsPerBlock)
ecp := ExtendedChainParams{
Params: cp,
AddressPrefix: addrPrefix,
ActualTicketPoolSize: actualTicketPoolSize,
}
str, err := exp.templates.execTemplateToString("parameters", struct {
Cp ExtendedChainParams
Version string
NetName string
}{
ecp,
exp.Version,
exp.NetName,
})
if err != nil {
log.Errorf("Template execute failure: %v", err)
exp.ErrorPage(w, "Something went wrong...", "and it's not your fault, try refreshing... that usually fixes things", false)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}