Skip to content

Commit 694eaee

Browse files
dmigwichappjc
authored andcommitted
Block visualization display at the newhome page (#660)
This PR introduces a graphical display of the blockchain's latest blocks and some network statistics about the current environment that dcrdata is run in i.e. mainnet, testnet, or simnet. The network statistics comprise Coin Supply, Dev reward, Project Fund, Locked Ticket Pool value in, Ticket(PoS) reward, Ticket Price, Difficulty, PoW reward and the hashrate. Mempool data is listed as the first block display on the Decred blockchain's graphical blocks view.
1 parent 3dcd1bb commit 694eaee

43 files changed

Lines changed: 1657 additions & 235 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎db/dbtypes/conversion.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package dbtypes
22

33
import (
44
"fmt"
5+
"math"
56

67
"github.com/decred/dcrd/chaincfg"
78
"github.com/decred/dcrd/wire"
@@ -83,3 +84,10 @@ func ChartGroupingToInterval(grouping ChartGrouping) (float64, error) {
8384
return -1, fmt.Errorf(`unknown chart grouping "%d"`, grouping)
8485
}
8586
}
87+
88+
// CalculateHashRate calculates the hashrate from the difficulty value and
89+
// the targetTimePerBlock in seconds. The hashrate returned is in form PetaHash
90+
// per second (PH/s).
91+
func CalculateHashRate(difficulty, targetTimePerBlock float64) float64 {
92+
return ((difficulty * math.Pow(2, 32)) / targetTimePerBlock) / 1000000
93+
}

‎db/dcrsqlite/apisource.go‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,6 +774,17 @@ func (db *wiredDB) GetSDiff(idx int) float64 {
774774
return sdiff
775775
}
776776

777+
// RetreiveDifficulty fetches the difficulty value in the last 24hrs or
778+
// immediately after 24hrs.
779+
func (db *wiredDB) RetreiveDifficulty(timestamp int64) float64 {
780+
sdiff, err := db.RetrieveDiff(timestamp)
781+
if err != nil {
782+
log.Errorf("Unable to retrieve difficulty: %v", err)
783+
return -1
784+
}
785+
return sdiff
786+
}
787+
777788
func (db *wiredDB) GetSDiffRange(idx0, idx1 int) []float64 {
778789
sdiffs, err := db.RetrieveSDiffRange(int64(idx0), int64(idx1))
779790
if err != nil {
@@ -1015,16 +1026,34 @@ func (db *wiredDB) GetExplorerBlocks(start int, end int) []*explorer.BlockBasic
10151026
return summaries
10161027
}
10171028

1029+
func (db *wiredDB) GetExplorerFullBlocks(start int, end int) []*explorer.BlockInfo {
1030+
if start < end {
1031+
return nil
1032+
}
1033+
summaries := make([]*explorer.BlockInfo, 0, start-end)
1034+
for i := start; i > end; i-- {
1035+
data := db.GetBlockVerbose(i, true)
1036+
block := new(explorer.BlockInfo)
1037+
if data != nil {
1038+
block = db.GetExplorerBlock(data.Hash)
1039+
}
1040+
summaries = append(summaries, block)
1041+
}
1042+
return summaries
1043+
}
1044+
10181045
func (db *wiredDB) GetExplorerBlock(hash string) *explorer.BlockInfo {
10191046
data := db.GetBlockVerboseByHash(hash, true)
10201047
if data == nil {
10211048
log.Error("Unable to get block for block hash " + hash)
10221049
return nil
10231050
}
10241051

1052+
b := makeExplorerBlockBasic(data)
1053+
10251054
// Explorer Block Info
10261055
block := &explorer.BlockInfo{
1027-
BlockBasic: makeExplorerBlockBasic(data),
1056+
BlockBasic: b,
10281057
Version: data.Version,
10291058
Confirmations: data.Confirmations,
10301059
StakeRoot: data.StakeRoot,
@@ -1041,6 +1070,7 @@ func (db *wiredDB) GetExplorerBlock(hash string) *explorer.BlockInfo {
10411070
PreviousHash: data.PreviousHash,
10421071
NextHash: data.NextHash,
10431072
StakeValidationHeight: db.params.StakeValidationHeight,
1073+
AllTxs: (uint32(b.Voters) + uint32(b.Transactions) + uint32(b.FreshStake)),
10441074
}
10451075

10461076
votes := make([]*explorer.TxBasic, 0, block.Voters)

‎db/dcrsqlite/sqlite.go‎

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ type DB struct {
6666
getStakeInfoWinnersSQL string
6767
getAllPoolValSize string
6868
getAllFeeInfoPerBlock string
69+
// returns difficulty in 24hrs or immediately after 24hrs.
70+
getDifficulty string
6971
}
7072

7173
// NewDB creates a new DB instance with pre-generated sql statements from an
@@ -79,29 +81,31 @@ func NewDB(db *sql.DB) (*DB, error) {
7981
}
8082

8183
// Ticket pool queries
82-
d.getPoolSQL = fmt.Sprintf(`select hash, poolsize, poolval, poolavg, winners`+
83-
` from %s where height = ?`, TableNameSummaries)
84-
d.getPoolByHashSQL = fmt.Sprintf(`select height, poolsize, poolval, poolavg, winners`+
85-
` from %s where hash = ?`, TableNameSummaries)
86-
d.getPoolRangeSQL = fmt.Sprintf(`select height, hash, poolsize, poolval, poolavg, winners `+
87-
`from %s where height between ? and ?`, TableNameSummaries)
88-
d.getPoolValSizeRangeSQL = fmt.Sprintf(`select poolsize, poolval `+
89-
`from %s where height between ? and ?`, TableNameSummaries)
90-
d.getAllPoolValSize = fmt.Sprintf(`select distinct poolsize, poolval, time `+
91-
`from %s order by time`, TableNameSummaries)
92-
d.getWinnersSQL = fmt.Sprintf(`select hash, winners from %s where height = ?`,
84+
d.getPoolSQL = fmt.Sprintf(`SELECT hash, poolsize, poolval, poolavg, winners`+
85+
` FROM %s WHERE height = ?`, TableNameSummaries)
86+
d.getPoolByHashSQL = fmt.Sprintf(`SELECT height, poolsize, poolval, poolavg, winners`+
87+
` FROM %s WHERE hash = ?`, TableNameSummaries)
88+
d.getPoolRangeSQL = fmt.Sprintf(`SELECT height, hash, poolsize, poolval, poolavg, winners `+
89+
`FROM %s WHERE height BETWEEN ? AND ?`, TableNameSummaries)
90+
d.getPoolValSizeRangeSQL = fmt.Sprintf(`SELECT poolsize, poolval `+
91+
`FROM %s WHERE height BETWEEN ? AND ?`, TableNameSummaries)
92+
d.getAllPoolValSize = fmt.Sprintf(`SELECT distinct poolsize, poolval, time `+
93+
`FROM %s ORDER BY time`, TableNameSummaries)
94+
d.getWinnersSQL = fmt.Sprintf(`SELECT hash, winners FROM %s WHERE height = ?`,
9395
TableNameSummaries)
94-
d.getWinnersByHashSQL = fmt.Sprintf(`select height, winners from %s where hash = ?`,
96+
d.getWinnersByHashSQL = fmt.Sprintf(`SELECT height, winners FROM %s WHERE hash = ?`,
9597
TableNameSummaries)
9698

97-
d.getSDiffSQL = fmt.Sprintf(`select sdiff from %s where height = ?`,
99+
d.getSDiffSQL = fmt.Sprintf(`SELECT sdiff FROM %s WHERE height = ?`,
98100
TableNameSummaries)
99-
d.getSDiffRangeSQL = fmt.Sprintf(`select sdiff from %s where height between ? and ?`,
101+
d.getDifficulty = fmt.Sprintf(`SELECT diff FROM %s WHERE time >= ? ORDER BY time LIMIT 1`,
102+
TableNameSummaries)
103+
d.getSDiffRangeSQL = fmt.Sprintf(`SELECT sdiff FROM %s WHERE height BETWEEN ? AND ?`,
100104
TableNameSummaries)
101105

102106
// Block queries
103-
d.getBlockSQL = fmt.Sprintf(`select * from %s where height = ?`, TableNameSummaries)
104-
d.getBlockByHashSQL = fmt.Sprintf(`select * from %s where hash = ?`, TableNameSummaries)
107+
d.getBlockSQL = fmt.Sprintf(`SELECT * FROM %s WHERE height = ?`, TableNameSummaries)
108+
d.getBlockByHashSQL = fmt.Sprintf(`SELECT * FROM %s WHERE hash = ?`, TableNameSummaries)
105109
d.getLatestBlockSQL = fmt.Sprintf(`SELECT * FROM %s ORDER BY height DESC LIMIT 0, 1`,
106110
TableNameSummaries)
107111
d.insertBlockSQL = fmt.Sprintf(`
@@ -110,23 +114,23 @@ func NewDB(db *sql.DB) (*DB, error) {
110114
) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
111115
`, TableNameSummaries)
112116

113-
d.getBlockSizeRangeSQL = fmt.Sprintf(`select size from %s where height between ? and ?`,
117+
d.getBlockSizeRangeSQL = fmt.Sprintf(`SELECT size FROM %s WHERE height BETWEEN ? AND ?`,
114118
TableNameSummaries)
115-
d.getBlockByTimeRangeSQL = fmt.Sprintf(`select * from %s where time between ? and ? ORDER BY time LIMIT ?`,
119+
d.getBlockByTimeRangeSQL = fmt.Sprintf(`SELECT * FROM %s WHERE time BETWEEN ? AND ? ORDER BY time LIMIT ?`,
116120
TableNameSummaries)
117-
d.getBlockByTimeSQL = fmt.Sprintf(`select * from %s where time = ?`,
121+
d.getBlockByTimeSQL = fmt.Sprintf(`SELECT * FROM %s WHERE time = ?`,
118122
TableNameSummaries)
119123

120-
d.getBestBlockHashSQL = fmt.Sprintf(`select hash from %s ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
121-
d.getBestBlockHeightSQL = fmt.Sprintf(`select height from %s ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
124+
d.getBestBlockHashSQL = fmt.Sprintf(`SELECT hash FROM %s ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
125+
d.getBestBlockHeightSQL = fmt.Sprintf(`SELECT height FROM %s ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
122126

123-
d.getBlockHashSQL = fmt.Sprintf(`select hash from %s where height = ?`, TableNameSummaries)
124-
d.getBlockHeightSQL = fmt.Sprintf(`select height from %s where hash = ?`, TableNameSummaries)
127+
d.getBlockHashSQL = fmt.Sprintf(`SELECT hash FROM %s WHERE height = ?`, TableNameSummaries)
128+
d.getBlockHeightSQL = fmt.Sprintf(`SELECT height FROM %s WHERE hash = ?`, TableNameSummaries)
125129

126130
// Stake info queries
127-
d.getStakeInfoExtendedSQL = fmt.Sprintf(`select * from %s where height = ?`,
131+
d.getStakeInfoExtendedSQL = fmt.Sprintf(`SELECT * FROM %s WHERE height = ?`,
128132
TableNameStakeInfo)
129-
d.getStakeInfoWinnersSQL = fmt.Sprintf(`select winners from %s where height = ?`,
133+
d.getStakeInfoWinnersSQL = fmt.Sprintf(`SELECT winners FROM %s WHERE height = ?`,
130134
TableNameStakeInfo)
131135
d.getLatestStakeInfoExtendedSQL = fmt.Sprintf(
132136
`SELECT * FROM %s ORDER BY height DESC LIMIT 0, 1`, TableNameStakeInfo)
@@ -651,7 +655,14 @@ func (db *DB) RetrieveBlockSummaryByTimeRange(minTime, maxTime int64, limit int)
651655
return blocks, nil
652656
}
653657

654-
// RetrieveSDiff returns the stake difficulty for block ind
658+
// RetrieveDiff returns the difficulty in the last 24hrs or immediately after 24hrs.
659+
func (db *DB) RetrieveDiff(timestamp int64) (float64, error) {
660+
var diff float64
661+
err := db.QueryRow(db.getDifficulty, timestamp).Scan(&diff)
662+
return diff, err
663+
}
664+
665+
// RetrieveSDiff returns the stake difficulty for block at the specified chain height.
655666
func (db *DB) RetrieveSDiff(ind int64) (float64, error) {
656667
var sdiff float64
657668
err := db.QueryRow(db.getSDiffSQL, ind).Scan(&sdiff)

‎explorer/explorer.go‎

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import (
2424
"github.com/decred/dcrdata/v3/blockdata"
2525
"github.com/decred/dcrdata/v3/db/dbtypes"
2626
"github.com/decred/dcrdata/v3/txhelpers"
27-
humanize "github.com/dustin/go-humanize"
2827
"github.com/go-chi/chi"
2928
"github.com/go-chi/chi/middleware"
3029
"github.com/rs/cors"
@@ -56,6 +55,8 @@ type explorerDataSourceLite interface {
5655
TxHeight(txid string) (height int64)
5756
BlockSubsidy(height int64, voters uint16) *dcrjson.GetBlockSubsidyResult
5857
GetSqliteChartsData() (map[string]*dbtypes.ChartsData, error)
58+
GetExplorerFullBlocks(start int, end int) []*BlockInfo
59+
RetreiveDifficulty(timestamp int64) float64
5960
}
6061

6162
// explorerDataSource implements extra data retrieval functions that require a
@@ -141,7 +142,7 @@ type explorerUI struct {
141142
templates templates
142143
wsHub *WebsocketHub
143144
NewBlockDataMtx sync.RWMutex
144-
NewBlockData *BlockBasic
145+
NewBlockData *BlockInfo
145146
ExtraInfo *HomeInfo
146147
MempoolData *MempoolInfo
147148
ChainParams *chaincfg.Params
@@ -236,7 +237,7 @@ func New(dataSource explorerDataSourceLite, primaryDataSource explorerDataSource
236237
}
237238
tmpls := []string{"home", "explorer", "mempool", "block", "tx", "address",
238239
"rawtx", "status", "parameters", "agenda", "agendas", "charts", "sidechains",
239-
"ticketpool"}
240+
"ticketpool", "nexthome"}
240241

241242
tempDefaults := []string{"extras"}
242243

@@ -301,7 +302,7 @@ func (exp *explorerUI) prePopulateChartsData() {
301302
log.Info("Done Pre-populating the charts data")
302303
}
303304

304-
func (exp *explorerUI) Store(blockData *blockdata.BlockData, _ *wire.MsgBlock) error {
305+
func (exp *explorerUI) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error {
305306
bData := blockData.ToBlockExplorerSummary()
306307

307308
// Update the charts data after every five blocks or if no charts data
@@ -310,35 +311,37 @@ func (exp *explorerUI) Store(blockData *blockdata.BlockData, _ *wire.MsgBlock) e
310311
go exp.prePopulateChartsData()
311312
}
312313

313-
// Lock for explorerUI's NewBlockData and ExtraInfo
314-
exp.NewBlockDataMtx.Lock()
315-
316-
newBlockData := &BlockBasic{
317-
Height: int64(bData.Height),
318-
Hash: blockData.Header.Hash,
319-
Voters: bData.Voters,
320-
FreshStake: bData.FreshStake,
321-
Size: int32(bData.Size),
322-
Transactions: bData.TxLen,
323-
BlockTime: bData.Time,
324-
FormattedTime: bData.FormattedTime,
325-
FormattedBytes: humanize.Bytes(uint64(bData.Size)),
326-
Revocations: uint32(bData.Revocations),
327-
}
328-
exp.NewBlockData = newBlockData
314+
// Returns the Block with some more data needed for the full block visualization.
315+
newBlockData := exp.blockData.GetExplorerBlock(msgBlock.BlockHash().String())
316+
targetTimePerBlock := float64(exp.ChainParams.TargetTimePerBlock)
317+
difficulty := blockData.Header.Difficulty
329318
bdHeight := newBlockData.Height
330319

320+
// last 24hr timestamp
321+
timestamp := time.Now().Add(-24 * time.Hour).Unix()
322+
// RetreiveDifficulty fetches the difficulty using the last 24hr timestamp,
323+
// whereby the difficulty can have a timestamp equal to the last 24hrs timestamp
324+
// or that is immediately greater than the 24hr timestamp.
325+
last24hrDifficulty := exp.blockData.RetreiveDifficulty(timestamp)
326+
last24HrHashRate := dbtypes.CalculateHashRate(last24hrDifficulty, targetTimePerBlock)
331327
stakePerc := blockData.PoolInfo.Value / dcrutil.Amount(blockData.ExtraInfo.CoinSupply).ToCoin()
332328

329+
// Lock for explorerUI's NewBlockData and ExtraInfo
330+
exp.NewBlockDataMtx.Lock()
331+
333332
// Update all ExtraInfo with latest data
333+
exp.NewBlockData = newBlockData
334+
exp.ExtraInfo.HashRate = dbtypes.CalculateHashRate(difficulty, targetTimePerBlock)
335+
exp.ExtraInfo.HashRateChange = 100 * (exp.ExtraInfo.HashRate - last24HrHashRate) / last24HrHashRate
336+
334337
exp.ExtraInfo.CoinSupply = blockData.ExtraInfo.CoinSupply
335338
exp.ExtraInfo.StakeDiff = blockData.CurrentStakeDiff.CurrentStakeDifficulty
336339
exp.ExtraInfo.NextExpectedStakeDiff = blockData.EstStakeDiff.Expected
337340
exp.ExtraInfo.NextExpectedBoundsMin = blockData.EstStakeDiff.Min
338341
exp.ExtraInfo.NextExpectedBoundsMax = blockData.EstStakeDiff.Max
339342
exp.ExtraInfo.IdxBlockInWindow = blockData.IdxBlockInWindow
340343
exp.ExtraInfo.IdxInRewardWindow = int(bdHeight % exp.ChainParams.SubsidyReductionInterval)
341-
exp.ExtraInfo.Difficulty = blockData.Header.Difficulty
344+
exp.ExtraInfo.Difficulty = difficulty
342345
exp.ExtraInfo.NBlockSubsidy.Dev = blockData.ExtraInfo.NextBlockSubsidy.Developer
343346
exp.ExtraInfo.NBlockSubsidy.PoS = blockData.ExtraInfo.NextBlockSubsidy.PoS
344347
exp.ExtraInfo.NBlockSubsidy.PoW = blockData.ExtraInfo.NextBlockSubsidy.PoW

‎explorer/explorerroutes.go‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,41 @@ func (exp *explorerUI) SideChains(w http.ResponseWriter, r *http.Request) {
106106
io.WriteString(w, str)
107107
}
108108

109+
// NextHome is the page handler for the "/nexthome" path
110+
func (exp *explorerUI) NextHome(w http.ResponseWriter, r *http.Request) {
111+
height := exp.blockData.GetHeight()
112+
113+
blocks := exp.blockData.GetExplorerFullBlocks(height, height-11)
114+
115+
exp.NewBlockDataMtx.RLock()
116+
exp.MempoolData.RLock()
117+
118+
str, err := exp.templates.execTemplateToString("nexthome", struct {
119+
Info *HomeInfo
120+
Mempool *MempoolInfo
121+
Blocks []*BlockInfo
122+
Version string
123+
NetName string
124+
}{
125+
exp.ExtraInfo,
126+
exp.MempoolData,
127+
blocks,
128+
exp.Version,
129+
exp.NetName,
130+
})
131+
exp.NewBlockDataMtx.RUnlock()
132+
exp.MempoolData.RUnlock()
133+
134+
if err != nil {
135+
log.Errorf("Template execute failure: %v", err)
136+
exp.StatusPage(w, defaultErrorCode, defaultErrorMessage, ErrorStatusType)
137+
return
138+
}
139+
w.Header().Set("Content-Type", "text/html")
140+
w.WriteHeader(http.StatusOK)
141+
io.WriteString(w, str)
142+
}
143+
109144
// Blocks is the page handler for the "/blocks" path
110145
func (exp *explorerUI) Blocks(w http.ResponseWriter, r *http.Request) {
111146
idx := exp.blockData.GetHeight()

‎explorer/explorertypes.go‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ type BlockInfo struct {
207207
TotalSent float64
208208
MiningFee dcrutil.Amount
209209
StakeValidationHeight int64
210+
AllTxs uint32
210211
}
211212

212213
// AddressTransactions collects the transactions for an address as AddressTx
@@ -312,6 +313,10 @@ type HomeInfo struct {
312313
NBlockSubsidy BlockSubsidy `json:"subsidy"`
313314
Params ChainParams `json:"params"`
314315
PoolInfo TicketPoolInfo `json:"pool_info"`
316+
TotalLockedDCR float64 `json:"total_locked_dcr"`
317+
HashRate float64 `json:"hash_rate"`
318+
// HashRateChange defines the hashrate change in 24hrs
319+
HashRateChange float64 `json:"hash_rate_change"`
315320
}
316321

317322
// BlockSubsidy is an implementation of dcrjson.GetBlockSubsidyResult
@@ -434,8 +439,8 @@ func ReduceAddressHistory(addrHist []*dbtypes.AddressRow) *AddressInfo {
434439

435440
// WebsocketBlock wraps the new block info for use in the websocket
436441
type WebsocketBlock struct {
437-
Block *BlockBasic `json:"block"`
438-
Extra *HomeInfo `json:"extra"`
442+
Block *BlockInfo `json:"block"`
443+
Extra *HomeInfo `json:"extra"`
439444
}
440445

441446
// TicketPoolInfo describes the live ticket pool

0 commit comments

Comments
 (0)
⌂ 换网址