-
Notifications
You must be signed in to change notification settings - Fork 16
/
router.go
639 lines (539 loc) · 17.4 KB
/
router.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
/**
*/
package main
import (
"context"
"encoding/hex"
"fmt"
"html/template"
"log"
"math/big"
"net/http"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/params"
"github.com/gorilla/mux"
)
// *********************** variable ********************************************
// NetworkHost for holding the host
var NetworkHost = "http://localhost:8545" // Ganache host
var client *ethclient.Client // for client to access globally
// *********************** structs *********************************************
// for overall ganache statistics
type sysInfo struct {
NumBlock string
NetworkID *big.Int
PendingTransactionCount uint
SuggestedGasPrice *big.Int
BlockDetails []blockInfo
AccountDetails []accountInfo
}
// for block details
type blockInfo struct {
Block string
BlockHash string
BlockNonce uint64
Transactions int
Transactionhash string
GasUsed uint64
MinedOn time.Time
Difficulty *big.Int
Size common.StorageSize
Gaslimit uint64
ParentHash string
UncleHash string
TxnStatus string
}
// for ganache Default Account Details
type accountInfo struct {
AccAddress string
AccBalance string
AccTXNCount uint64
AccIndex int
}
// for ganache Default Account Details
type accDetails struct {
AccAddress string
AccBalance string
AccTXNCount uint64
}
// for transaction details
type txDetails struct {
TxHash string
TxGas uint64
TxGasPrice uint64
TxNonce uint64
TxToAddress string
TxFromAddress string
TxData string
TxValue *big.Int
}
// for transaction details
type txPages struct {
BlockHash string
BlockNumber *big.Int
Totaltransactions int
TransactionStatus string
TxDetails []txDetails
}
// for error logs
type txLogs struct {
Status uint64
Log string
ErrorMsg error
Host string
}
// *********************** Utility ******************************************
func weiToEther(wei *big.Int) *big.Float {
return new(big.Float).Quo(new(big.Float).SetInt(wei), big.NewFloat(params.Ether))
}
// *********************** block details ***************************************
/*
blockInDetails function: fetches the block details based on hash
*/
func blockInDetails(w http.ResponseWriter, r *http.Request) {
/* local variables */
var blockHash common.Hash
// parsing the request
for _, qs := range r.URL.Query() {
blockHash = common.HexToHash(qs[0])
}
// client request for the block
blockDetails, blockByHashErr := client.BlockByHash(context.Background(), blockHash)
kickBack(blockByHashErr,
"Reason: `@BlockByHash` failed. Couldn't able to fetch block.")
// block creation time
creationTime := time.Unix(int64(blockDetails.Time()), 0)
// loading data for rendering
data := blockInfo{
Block: blockDetails.Number().String(),
BlockHash: blockDetails.Hash().Hex(),
BlockNonce: blockDetails.Nonce(),
Transactions: len(blockDetails.Transactions()),
GasUsed: blockDetails.GasUsed(),
MinedOn: creationTime,
Difficulty: blockDetails.Difficulty(),
Size: blockDetails.Size(),
Gaslimit: blockDetails.GasLimit(),
ParentHash: blockDetails.ParentHash().String(),
UncleHash: blockDetails.UncleHash().String(),
}
// render
tmpl := template.Must(template.ParseFiles("template/blockDetails.html"))
tmpl.Execute(w, data)
}
// *********************** blockshomepage **************************************
/*
blockPage function: fetches the block details based on number for the block
page
*/
func blockPage(w http.ResponseWriter, bn *big.Int) blockInfo {
var receipt *types.Receipt
var receiptStatus string
// getting block based on given number
block, _ := client.BlockByNumber(context.Background(), bn)
// kickBack(w, r, blockByNumberErr,
// "Reason: `@BlockByNumber` failed. Couldn't able to fetch block.")
// block creation time
creationTime := time.Unix(int64(block.Time()), 0)
var tempTxn string
_ = tempTxn
// getting transaction details
for _, tx := range block.Transactions() {
tempTxn = tx.Hash().String()
receipt, _ = client.TransactionReceipt(context.Background(), tx.Hash())
}
if receipt.Status == uint64(1) {
receiptStatus = "SUCCESSFUL"
} else {
receiptStatus = "FAILED"
}
// loading data for rendering
blockData := blockInfo{
Block: bn.String(),
BlockHash: block.Hash().String(),
BlockNonce: block.Nonce(),
Transactions: len(block.Transactions()),
Transactionhash: tempTxn,
GasUsed: block.GasUsed(),
MinedOn: creationTime,
TxnStatus: receiptStatus,
}
return blockData
}
// *********************** homepage **************************************
/*
accountsBalance function: fetches the account details and their balance
*/
func getAccountDetails(account common.Address, itr int) accountInfo {
// load all the block details
balance, err := client.BalanceAt(context.Background(), account, nil)
if err != nil {
log.Fatal(err)
}
balanceETH := weiToEther(balance)
//fmt.Println(balanceETH)
// Here it fetches the latest block for the connected client (i.e., ganache)
numBlock, headerByNumberErr := client.HeaderByNumber(context.Background(), nil)
kickBack(headerByNumberErr, "Reason:`@HeaderByNumber` failed. Make sure GANACHE runs @ localhost")
nonce, _ := client.NonceAt(context.Background(), account, numBlock.Number)
//fmt.Println(state)
// loading account data for rendering
accountData := accountInfo{
AccAddress: account.String(),
AccBalance: balanceETH.String() + " ETH",
AccTXNCount: nonce,
AccIndex: itr,
}
return accountData
}
/*
accountsBalance function: fetches the account details and their balance
*/
func showBalanceInfo(w http.ResponseWriter, r *http.Request) {
var qss string
// parsing the request
for _, qs := range r.URL.Query() {
qss = qs[0]
}
// load all the block details
balance, err := client.BalanceAt(context.Background(), common.BytesToAddress(common.FromHex(qss)), nil)
if err != nil {
log.Fatal(err)
}
balanceETH := weiToEther(balance)
//fmt.Println(balanceETH)
// Here it fetches the latest block for the connected client (i.e., ganache)
numBlock, headerByNumberErr := client.HeaderByNumber(context.Background(), nil)
kickBack(headerByNumberErr, "Reason:`@HeaderByNumber` failed. Make sure GANACHE runs @ localhost")
nonce, _ := client.NonceAt(context.Background(), common.BytesToAddress(common.FromHex(qss)), numBlock.Number)
//fmt.Println(state)
// loading account data for rendering
accountData := accDetails{
AccAddress: qss,
AccBalance: balanceETH.String() + " ETH",
AccTXNCount: nonce,
}
// render
tmpl := template.Must(template.ParseFiles("template/checkBalance.html"))
tmpl.Execute(w, accountData)
}
// *********************** txpage **********************************************
/*
txPage function: provide the complete transaction details based on the
block number or block hash.
*/
func txPage(w http.ResponseWriter, r *http.Request) {
/* local variables */
var qss string
var block *types.Block
var listTxDetails []txDetails
var err error
var toAddress string
var execStatus bool
var log txLogs
// parsing the request
for _, qs := range r.URL.Query() {
qss = qs[0]
}
bn, strConvErr := strconv.Atoi(qss) // converting string into number to pass in client call
// has to accept either number or hash, so validating
// TODO: what if some other happens, has to validate the err
if strConvErr != nil {
hash := common.HexToHash(qss)
// getting block with hash
block, err = client.BlockByHash(context.Background(), hash)
// check whether block number exists or not
if err != nil {
execStatus = true
log = txLogs{
Status: 404,
Log: "Block with given hash is not available in the network",
ErrorMsg: err,
Host: "homepage",
}
} else {
execStatus = false
}
} else {
// getting block with number
block, err = client.BlockByNumber(context.Background(), big.NewInt(int64(bn)))
// check whether block hash exists or not
if err != nil {
execStatus = true
log = txLogs{
Status: 404,
Log: "Block with given number is not available in the network",
ErrorMsg: err,
Host: "homepage",
}
} else {
execStatus = false
}
}
// based on block availability execute
if execStatus {
// render
tmpl := template.Must(template.ParseFiles("template/404.html"))
tmpl.Execute(w, log)
} else {
// getting transaction details
for _, tx := range block.Transactions() {
// check for toAddress
receipt, _ := client.TransactionReceipt(context.Background(), tx.Hash())
if tx.To() == nil {
toAddress = receipt.ContractAddress.Hex() + " [CONTRACT CREATION]"
} else {
toAddress = tx.To().Hex()
}
signer := types.LatestSignerForChainID(tx.ChainId())
sender, _ := signer.Sender(tx)
fmt.Println("From inside: ", sender.Hex())
dt := txDetails{
TxHash: tx.Hash().Hex(),
TxGas: tx.Gas(),
TxGasPrice: tx.GasPrice().Uint64(),
TxNonce: tx.Nonce(),
TxToAddress: toAddress,
TxFromAddress: sender.Hex(),
TxData: hex.EncodeToString(tx.Data()),
TxValue: tx.Value(),
}
// since transaction are multiple, loading it into an array
listTxDetails = append(listTxDetails, dt)
}
// updating final data into struct for rendering
data := txPages{
BlockNumber: block.Number(),
BlockHash: block.Hash().Hex(),
Totaltransactions: 1,
TxDetails: listTxDetails,
}
// render
tmpl := template.Must(template.ParseFiles("template/txPage.html"))
tmpl.Execute(w, data)
}
}
// /*
// txDetailsPage function: provide the complete transaction details based on the
// transaction hash.
// */
func txDetailsPage(w http.ResponseWriter, r *http.Request) {
/* local variables */
var qss string
var tx *types.Transaction
var listTxDetails []txDetails
var err error
var toAddress string
var execStatus bool
var log txLogs
var receipt *types.Receipt
var receiptStatus string
// parsing the request
for _, qs := range r.URL.Query() {
qss = qs[0]
}
_, strConvErr := strconv.Atoi(qss) // converting string into number to pass in client call
// has to accept either number or hash, so validating
// TODO: what if some other happens, has to validate the err
if strConvErr != nil {
hash := common.HexToHash(qss)
// getting txn with hash
tx, _, err = client.TransactionByHash(context.Background(), hash)
receipt, _ = client.TransactionReceipt(context.Background(), hash)
if receipt != nil && receipt.Status == uint64(1) {
receiptStatus = "SUCCESSFUL"
} else {
receiptStatus = "FAILED"
}
fmt.Println("Transaction Status : ", receiptStatus)
// fmt.Println("Value : ", tx.Value())
// fmt.Println("contract address : ", receipt.ContractAddress)
// check whether block number exists or not
if err != nil {
execStatus = true
log = txLogs{
Status: 404,
Log: "Txn with given hash is not available in the network",
ErrorMsg: err,
Host: "homepage",
}
} else {
execStatus = false
}
}
// based on block availability execute
if execStatus || err != nil {
// render
tmpl := template.Must(template.ParseFiles("template/404.html"))
tmpl.Execute(w, log)
} else {
// getting transaction details
// check for toAddress
if tx.To() == nil {
toAddress = receipt.ContractAddress.Hex() + " [CONTRACT CREATION]"
} else {
toAddress = tx.To().Hex()
}
signer := types.LatestSignerForChainID(tx.ChainId())
sender, _ := signer.Sender(tx)
dt := txDetails{
TxHash: tx.Hash().Hex(),
TxGas: tx.Gas(),
TxGasPrice: tx.GasPrice().Uint64(),
TxNonce: tx.Nonce(),
TxToAddress: toAddress,
TxFromAddress: sender.Hex(),
TxData: hex.EncodeToString(tx.Data()),
TxValue: tx.Value(),
}
// since transaction are multiple, loading it into an array
listTxDetails = append(listTxDetails, dt)
// updating final data into struct for rendering
data := txPages{
BlockNumber: receipt.BlockNumber,
BlockHash: receipt.BlockHash.Hex(),
Totaltransactions: 1,
TransactionStatus: receiptStatus,
TxDetails: listTxDetails,
}
// render
tmpl := template.Must(template.ParseFiles("template/txPage.html"))
tmpl.Execute(w, data)
}
}
// *********************** txDetails *******************************************
// *********************** On Account of failure *******************************
/*
kickBack function: kickback to 404 if any invalid request or failure happens
*/
func kickBackErr(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("template/404.html"))
tmpl.Execute(w, nil)
}
func kickBack(err error, msg string) {
if err != nil {
fmt.Println("/******** ERROR ********************************************/")
fmt.Printf("Error: %v", err)
fmt.Printf("Reason: %v", msg)
panic(err)
}
}
// *********************** homepage ********************************************
/*
homePage function: serves the content for the main home page.
*/
func homePage(w http.ResponseWriter, r *http.Request) {
/* local variables */
var _blockdetails []blockInfo // to hold the blockNumber
var _accountDetails []accountInfo // to hold the blockNumber
var clientErr error
// parsing the request
for _, qs := range r.URL.Query() {
NetworkHost = qs[0]
}
// updating the client
client, clientErr = ethclient.Dial(NetworkHost)
if clientErr != nil {
log := txLogs{
Status: 404,
Log: "Host provided is invalid. Client Error",
ErrorMsg: clientErr,
}
tmpl := template.Must(template.ParseFiles("template/404.html"))
tmpl.Execute(w, log)
} else {
// Here it fetches the latest block for the connected client (i.e., ganache)
numBlock, headerByNumberErr := client.HeaderByNumber(context.Background(), nil)
kickBack(headerByNumberErr, "Reason:`@HeaderByNumber` failed. Make sure GANACHE runs @ localhost")
// Here it fetches the NetworkID for the connected client (i.e., ganache)
networkID, networkIDErr := client.NetworkID(context.Background())
kickBack(networkIDErr, "Reason: `@NetworkID` failed. Make sure GANACHE runs @ localhost")
// Here it fetches the pending transaction for the connected client (i.e., ganache)
pendingTxCount, _ := client.PendingTransactionCount(context.Background())
// Here it fetches the suggested gas price for the connected client (i.e., ganache)
suggestedGasPrice, suggestGasPriceError := client.SuggestGasPrice(context.Background())
kickBack(suggestGasPriceError, "Reason: `@SuggestGasPrice` failed. Couldn't able to fetch Suggested Gas Price")
// Here it fetches only the lasted 5 block for the home page
for x := numBlock.Number.Int64(); x > (numBlock.Number.Int64() - 5); x-- {
if x < 1 {
// Todo : break here to overcome negativity
break
} else {
// load all the block details
_blockdetails = append(_blockdetails, blockPage(w, big.NewInt(x)))
}
}
clientGanache := newClient(NetworkHost)
var accounts []string
err := clientGanache.call("eth_accounts", &accounts)
if err != nil {
log.Fatal(err)
}
//fmt.Println(accounts)
// getting account details
itr := 0
for _, acc := range accounts {
// check for toAddress
account := common.HexToAddress(acc)
_accountDetails = append(_accountDetails, getAccountDetails(account, itr))
itr += 1
}
// data: values to be rendered
data := sysInfo{
NumBlock: numBlock.Number.String(),
NetworkID: networkID,
PendingTransactionCount: pendingTxCount,
SuggestedGasPrice: suggestedGasPrice,
BlockDetails: _blockdetails,
AccountDetails: _accountDetails,
}
// mux render
tmpl := template.Must(template.ParseFiles("template/index.html"))
tmpl.Execute(w, data)
}
}
// *********************** welcome page ****************************************
/*
welcomePage function: serves the welcome page.
*/
func welcomePage(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("template/welcome.html"))
tmpl.Execute(w, nil)
}
// *********************** main ************************************************
/*
main: Main Handler, handles all the incoming request and maps for a route.
*/
func main() {
fmt.Println("!!!!INITIALIZING SERVER!!!!")
// mux router
gorilla := mux.NewRouter()
// network client activation
client, _ = ethclient.Dial(NetworkHost)
// for the static file handling, all the assets files will be loaded into the static folder
staticFileHandler := http.FileServer(http.Dir("static"))
// routes the all the static accessing url to the static folder
gorilla.PathPrefix("/static/").Handler(http.StripPrefix("/static/", staticFileHandler))
// controller
gorilla.HandleFunc("/homepage", homePage)
gorilla.HandleFunc("/txpage", txPage)
gorilla.HandleFunc("/txinfo", txDetailsPage)
gorilla.HandleFunc("/blockdetails", blockInDetails)
gorilla.HandleFunc("/accInfo", showBalanceInfo)
gorilla.HandleFunc("/", welcomePage)
// http server
// Note: Here gorilla is like passing our own server handler into net/http, by default its false
srv := &http.Server{
Handler: gorilla,
Addr: "127.0.0.1:5051",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
fmt.Println("!!!! SERVER STARTED at ADDRESS : 127.0.0.1:5051 !!!!")
log.Fatal(srv.ListenAndServe())
}