forked from decred/dcrdata
/
explorerroutes.go
418 lines (383 loc) · 13.5 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
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package explorer
import (
"io"
"net/http"
"strconv"
"github.com/decred/dcrd/chaincfg/chainhash"
)
// 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-6)
exp.NewBlockDataMtx.Lock()
exp.MempoolData.RLock()
str, err := templateExecToString(exp.templates[homeTemplateIndex], "home", struct {
Info *HomeInfo
Mempool *MempoolInfo
Blocks []*BlockBasic
Version string
}{
exp.ExtraInfo,
exp.MempoolData,
blocks,
exp.Version,
})
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 || height-rows < 0 {
rows = minExplorerRows
}
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 := templateExecToString(exp.templates[rootTemplateIndex], "explorer", struct {
Data []*BlockBasic
BestBlock int
Version string
}{
summaries,
idx,
exp.Version,
})
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
}
pageData := struct {
Data *BlockInfo
ConfirmHeight int64
Version string
}{
data,
exp.NewBlockData.Height - data.Confirmations,
exp.Version,
}
str, err := templateExecToString(exp.templates[blockTemplateIndex], "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", "/block/"+hash)
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
}
if !exp.liteMode {
// 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],
}
}
}
pageData := struct {
Data *TxInfo
ConfirmHeight int64
Version string
}{
tx,
exp.NewBlockData.Height - tx.Confirmations,
exp.Version,
}
str, err := templateExecToString(exp.templates[txTemplateIndex], "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", "/tx/"+hash)
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) {
// 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
}
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)
if errH != nil {
log.Errorf("Unable to get address %s history: %v", address, errH)
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
}
confirmHeights := make([]int64, len(addrData.Transactions))
if addrData == nil {
exp.ErrorPage(w, "Something went wrong...", "could not find that address", false)
}
addrData.Fullmode = true
pageData := struct {
Data *AddressInfo
ConfirmHeight []int64
Version string
}{
addrData,
confirmHeights,
exp.Version,
}
str, err := templateExecToString(exp.templates[addressTemplateIndex], "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.WriteHeader(http.StatusOK)
io.WriteString(w, str)
return
}
// Generate AddressInfo skeleton from the address table rows
addrData = ReduceAddressHistory(addrHist)
if addrData == nil {
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
}
addrData.Limit, addrData.Offset = limitN, offsetAddrOuts
addrData.KnownFundingTxns = balance.NumSpent + balance.NumUnspent
addrData.Balance = balance
addrData.Path = r.URL.Path
addrData.KnownTransactions = (balance.NumSpent * 2) + balance.NumUnspent
addrData.NumTransactions = int64(len(addrData.Transactions))
if addrData.NumTransactions > addrData.Limit {
addrData.NumTransactions = addrData.Limit
}
addrData.Fullmode = true
// still need []*AddressTx filled out and NumUnconfirmed
// 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
}
addrData.NumUnconfirmed, err = exp.blockData.CountUnconfirmedTransactions(address, MaxUnconfirmedPossible)
if err != nil {
log.Warnf("SearchRawTransactionsForUnconfirmedTransactions failed for address %s: %v", address, err)
}
}
confirmHeights := make([]int64, len(addrData.Transactions))
for i, v := range addrData.Transactions {
confirmHeights[i] = exp.NewBlockData.Height - int64(v.Confirmations)
}
pageData := struct {
Data *AddressInfo
ConfirmHeight []int64
Version string
}{
addrData,
confirmHeights,
exp.Version,
}
str, err := templateExecToString(exp.templates[addressTemplateIndex], "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", "/address/"+address)
w.WriteHeader(http.StatusOK)
io.WriteString(w, str)
}
func (exp *explorerUI) DecodeTxPage(w http.ResponseWriter, r *http.Request) {
str, err := templateExecToString(exp.templates[decodeTxTemplateIndex], "rawtx", struct {
Version string
}{
exp.Version,
})
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 := templateExecToString(exp.templates[errorTemplateIndex], "error", struct {
ErrorCode string
ErrorString string
Version string
}{
code,
message,
exp.Version,
})
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)
}