forked from gobitfly/eth2-beaconchain-explorer
/
search.go
416 lines (401 loc) · 15.2 KB
/
search.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
package handlers
import (
"encoding/hex"
"encoding/json"
"eth2-exporter/db"
"eth2-exporter/templates"
"eth2-exporter/types"
"eth2-exporter/utils"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/lib/pq"
)
const searchValidatorsResultLimit = 300
var transactionLikeRE = regexp.MustCompile(`^[0-9a-fA-F]{64}$`)
var searchLikeRE = regexp.MustCompile(`^[0-9a-fA-F]{0,96}$`)
var thresholdHexLikeRE = regexp.MustCompile(`^[0-9a-fA-F]{5,96}$`)
// Search handles search requests
func Search(w http.ResponseWriter, r *http.Request) {
search := r.FormValue("search")
_, err := strconv.Atoi(search)
if err == nil {
http.Redirect(w, r, "/block/"+search, http.StatusMovedPermanently)
return
}
search = strings.Replace(search, "0x", "", -1)
if utils.IsValidEth1Tx(search) {
http.Redirect(w, r, "/tx/"+search, http.StatusMovedPermanently)
} else if len(search) == 96 {
http.Redirect(w, r, "/validator/"+search, http.StatusMovedPermanently)
} else if utils.IsValidEth1Address(search) {
http.Redirect(w, r, "/address/"+search, http.StatusMovedPermanently)
} else {
w.Header().Set("Content-Type", "text/html")
templateFiles := append(layoutTemplateFiles, "searchnotfound.html")
var searchNotFoundTemplate = templates.GetTemplate(templateFiles...)
data := InitPageData(w, r, "search", "/search", "", templateFiles)
if handleTemplateError(w, r, "search.go", "Search", "", searchNotFoundTemplate.ExecuteTemplate(w, "layout", data)) != nil {
return // an error has occurred and was processed
}
}
}
// SearchAhead handles responses for the frontend search boxes
func SearchAhead(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
searchType := vars["type"]
search := vars["search"]
search = strings.Replace(search, "0x", "", -1)
search = strings.Replace(search, "0X", "", -1)
var err error
logger := logger.WithField("searchType", searchType)
var result interface{}
switch searchType {
case "slots":
if len(search) <= 1 {
break
}
result = &types.SearchAheadSlotsResult{}
if searchLikeRE.MatchString(search) {
if _, convertErr := strconv.Atoi(search); convertErr == nil {
err = db.ReaderDb.Select(result, `
SELECT slot, ENCODE(blockroot, 'hex') AS blockroot
FROM blocks
WHERE slot = $1
ORDER BY slot LIMIT 10`, search)
} else if len(search) == 64 {
blockHash, err := hex.DecodeString(search)
if err != nil {
logger.Errorf("error parsing blockHash to int: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
err = db.ReaderDb.Select(result, `
SELECT slot, ENCODE(blockroot, 'hex') AS blockroot
FROM blocks
WHERE blockroot = $1 OR
stateroot = $1
ORDER BY slot LIMIT 10`, blockHash)
if err != nil {
logger.Errorf("error reading block root: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
}
case "blocks":
number, err := strconv.ParseUint(search, 10, 64)
if err == nil {
block, err := db.BigtableClient.GetBlockFromBlocksTable(number)
if err == nil {
result = &types.SearchAheadBlocksResult{{
Block: block.Number,
Hash: fmt.Sprintf("%#x", block.Hash),
}}
}
}
case "graffiti":
graffiti := &types.SearchAheadGraffitiResult{}
err = db.ReaderDb.Select(graffiti, `
SELECT graffiti, count(*)
FROM blocks
WHERE graffiti_text ILIKE LOWER($1)
GROUP BY graffiti
ORDER BY count desc
LIMIT 10`, "%"+search+"%")
if err == nil {
for i := range *graffiti {
(*graffiti)[i].Graffiti = utils.FormatGraffitiString((*graffiti)[i].Graffiti)
}
}
result = graffiti
case "transactions":
result = &types.SearchAheadTransactionsResult{}
if transactionLikeRE.MatchString(strings.ToLower(strings.Replace(search, "0x", "", -1))) {
txHash, txHashErr := hex.DecodeString(strings.ToLower(strings.Replace(search, "0x", "", -1)))
if txHashErr != nil {
logger.Errorf("error parsing txHash %v: %v", search, txHashErr)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
var tx *types.Eth1TransactionIndexed
tx, err = db.BigtableClient.GetIndexedEth1Transaction(txHash)
if err == nil && tx != nil {
result = &types.SearchAheadTransactionsResult{{TxHash: fmt.Sprintf("%x", tx.Hash)}}
}
}
case "epochs":
result = &types.SearchAheadEpochsResult{}
err = db.ReaderDb.Select(result, "SELECT epoch FROM epochs WHERE CAST(epoch AS text) LIKE $1 ORDER BY epoch LIMIT 10", search+"%")
case "validators":
// find all validators that have a index, publickey or name like the search-query
result = &types.SearchAheadValidatorsResult{}
indexNumeric, errParse := strconv.ParseInt(search, 10, 64)
if errParse == nil { // search the validator by its index
err = db.ReaderDb.Select(result, `SELECT validatorindex AS index, pubkeyhex as pubkey FROM validators WHERE validatorindex = $1`, indexNumeric)
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
} else if thresholdHexLikeRE.MatchString(search) {
err = db.ReaderDb.Select(result, `SELECT validatorindex AS index, pubkeyhex as pubkey FROM validators WHERE pubkeyhex LIKE LOWER($1 || '%')`, search)
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
} else {
err = db.ReaderDb.Select(result, `
SELECT validatorindex AS index, pubkeyhex AS pubkey
FROM validators
LEFT JOIN validator_names ON validators.pubkey = validator_names.publickey
WHERE LOWER(validator_names.name) LIKE LOWER($1)
ORDER BY index LIMIT 10`, search+"%")
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
case "eth1_addresses":
// start := time.Now()
if len(search) <= 1 {
break
}
if len(search)%2 != 0 {
search = search[:len(search)-1]
}
if searchLikeRE.MatchString(search) {
eth1AddressHash, err := hex.DecodeString(search)
if err != nil {
logger.Errorf("error parsing eth1AddressHash to hash: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
result, err = db.BigtableClient.SearchForAddress(eth1AddressHash, 10)
if err != nil {
logger.Errorf("error searching for eth1AddressHash: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
} else {
result = []*types.Eth1AddressSearchItem{}
}
// logger.WithFields(logrus.Fields{
// "duration": time.Since(start),
// }).Infof("finished searching for eth1_addresses")
case "indexed_validators":
// find all validators that have a publickey or index like the search-query
result = &types.SearchAheadValidatorsResult{}
indexNumeric, errParse := strconv.ParseInt(search, 10, 64)
if errParse == nil { // search the validator by its index
err = db.ReaderDb.Select(result, `SELECT validatorindex AS index, pubkeyhex as pubkey FROM validators WHERE validatorindex = $1`, indexNumeric)
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
} else if thresholdHexLikeRE.MatchString(search) {
err = db.ReaderDb.Select(result, `SELECT validatorindex AS index, pubkeyhex as pubkey FROM validators WHERE pubkeyhex LIKE LOWER($1 || '%')`, search)
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
} else {
err = db.ReaderDb.Select(result, `
SELECT validatorindex AS index, pubkeyhex AS pubkey
FROM validators
LEFT JOIN validator_names ON validators.pubkey = validator_names.publickey
WHERE LOWER(validator_names.name) LIKE LOWER($1)
ORDER BY index LIMIT 10`, search+"%")
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
case "indexed_validators_by_eth1_addresses":
if len(search) <= 1 || len(search) > 40 {
break
}
if len(search)%2 != 0 {
search = search[:len(search)-1]
}
if searchLikeRE.MatchString(search) {
// find validators per eth1-address (limit result by N addresses and M validators per address)
result = &[]struct {
Eth1Address string `db:"from_address" json:"eth1_address"`
ValidatorIndices pq.Int64Array `db:"validatorindices" json:"validator_indices"`
Count uint64 `db:"count" json:"-"`
}{}
eth1AddressHash, err := hex.DecodeString(search)
if err != nil {
logger.Errorf("error parsing eth1AddressHash to hex: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
if len(eth1AddressHash) == 20 {
// if it is an eth1-address just search for exact match
err = db.ReaderDb.Select(result, `
SELECT from_address, COUNT(*), ARRAY_AGG(validatorindex) validatorindices FROM (
SELECT
DISTINCT ON(validatorindex) validatorindex,
ENCODE(from_address::bytea, 'hex') as from_address,
DENSE_RANK() OVER (PARTITION BY from_address ORDER BY validatorindex) AS validatorrow,
DENSE_RANK() OVER (ORDER BY from_address) AS addressrow
FROM eth1_deposits
INNER JOIN validators ON validators.pubkey = eth1_deposits.publickey
WHERE from_address = $1
) a
WHERE validatorrow <= $2 AND addressrow <= 10
GROUP BY from_address
ORDER BY count DESC`, eth1AddressHash, searchValidatorsResultLimit)
} else if len(eth1AddressHash) <= 16 {
// if the lenght is less then 32 use byte-wise comparison
err = db.ReaderDb.Select(result, `
SELECT from_address, COUNT(*), ARRAY_AGG(validatorindex) validatorindices FROM (
SELECT
DISTINCT ON(validatorindex) validatorindex,
ENCODE(from_address::bytea, 'hex') as from_address,
DENSE_RANK() OVER (PARTITION BY from_address ORDER BY validatorindex) AS validatorrow,
DENSE_RANK() OVER (ORDER BY from_address) AS addressrow
FROM eth1_deposits
INNER JOIN validators ON validators.pubkey = eth1_deposits.publickey
WHERE from_address LIKE $1 || '%'::bytea
) a
WHERE validatorrow <= $2 AND addressrow <= 10
GROUP BY from_address
ORDER BY count DESC`, eth1AddressHash, searchValidatorsResultLimit)
} else {
// otherwise use hex (see BIDS-1570)
err = db.ReaderDb.Select(result, `
SELECT from_address, COUNT(*), ARRAY_AGG(validatorindex) validatorindices FROM (
SELECT
DISTINCT ON(validatorindex) validatorindex,
ENCODE(from_address::bytea, 'hex') as from_address,
DENSE_RANK() OVER (PARTITION BY from_address ORDER BY validatorindex) AS validatorrow,
DENSE_RANK() OVER (ORDER BY from_address) AS addressrow
FROM eth1_deposits
INNER JOIN validators ON validators.pubkey = eth1_deposits.publickey
WHERE encode(from_address,'hex') LIKE $1
) a
WHERE validatorrow <= $2 AND addressrow <= 10
GROUP BY from_address
ORDER BY count DESC`, search+"%", searchValidatorsResultLimit)
}
if err != nil {
logger.Errorf("error reading result data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
case "count_indexed_validators_by_eth1_address":
if len(search) <= 1 {
break
}
if len(search)%2 != 0 {
search = search[:len(search)-1]
}
if searchLikeRE.MatchString(search) {
// find validators per eth1-address (limit result by N addresses and M validators per address)
result = &[]struct {
Eth1Address string `db:"from_address" json:"eth1_address"`
Count uint64 `db:"count" json:"count"`
}{}
eth1AddressHash, err := hex.DecodeString(search)
if err != nil {
logger.Errorf("error parsing eth1AddressHash to hex: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
err = db.ReaderDb.Select(result, `
SELECT from_address, COUNT(*) FROM (
SELECT
DISTINCT ON(validatorindex) validatorindex,
ENCODE(from_address::bytea, 'hex') as from_address
FROM eth1_deposits
INNER JOIN validators ON validators.pubkey = eth1_deposits.publickey
WHERE from_address LIKE $1 || '%'::bytea
) a
GROUP BY from_address`, eth1AddressHash)
if err != nil {
logger.Errorf("error retrieving count of indexed validators by address data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
case "indexed_validators_by_graffiti":
// find validators per graffiti (limit result by N graffities and M validators per graffiti)
res := []struct {
Graffiti string `db:"graffiti" json:"graffiti"`
ValidatorIndices pq.Int64Array `db:"validatorindices" json:"validator_indices"`
Count uint64 `db:"count" json:"-"`
}{}
err = db.ReaderDb.Select(&res, `
SELECT graffiti, COUNT(*), ARRAY_AGG(validatorindex) validatorindices FROM (
SELECT
DISTINCT ON(validatorindex) validatorindex,
graffiti,
DENSE_RANK() OVER(PARTITION BY graffiti ORDER BY validatorindex) AS validatorrow,
DENSE_RANK() OVER(ORDER BY graffiti) AS graffitirow
FROM blocks
LEFT JOIN validators ON blocks.proposer = validators.validatorindex
WHERE graffiti_text ILIKE LOWER($1)
) a
WHERE validatorrow <= $2 AND graffitirow <= 10
GROUP BY graffiti
ORDER BY count DESC`, "%"+search+"%", searchValidatorsResultLimit)
if err == nil {
for i := range res {
res[i].Graffiti = utils.FormatGraffitiString(res[i].Graffiti)
}
}
result = &res
case "indexed_validators_by_name":
// find validators per name (limit result by N names and N validators per name)
res := []struct {
Name string `db:"name" json:"name"`
ValidatorIndices pq.Int64Array `db:"validatorindices" json:"validator_indices"`
Count uint64 `db:"count" json:"-"`
}{}
err = db.ReaderDb.Select(&res, `
SELECT name, COUNT(*), ARRAY_AGG(validatorindex) validatorindices FROM (
SELECT
validatorindex,
validator_names.name,
DENSE_RANK() OVER(PARTITION BY validator_names.name ORDER BY validatorindex) AS validatorrow,
DENSE_RANK() OVER(PARTITION BY validator_names.name) AS namerow
FROM validators
LEFT JOIN validator_names ON validators.pubkey = validator_names.publickey
WHERE LOWER(validator_names.name) LIKE LOWER($1)
) a
WHERE validatorrow <= $2 AND namerow <= 10
GROUP BY name
ORDER BY count DESC, name DESC`, "%"+search+"%", searchValidatorsResultLimit)
if err == nil {
for i := range res {
res[i].Name = string(utils.FormatValidatorName(res[i].Name))
}
}
result = &res
default:
http.Error(w, "Not found", 404)
return
}
if err != nil {
logger.WithError(err).WithField("searchType", searchType).Error("error doing query for searchAhead")
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
err = json.NewEncoder(w).Encode(result)
if err != nil {
logger.WithError(err).Error("error encoding searchAhead")
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
}
}