Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion block.go
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,7 @@ func (c *Chain) RecentBlockStats(samples int) (hashrate float64, avgBlockTime fl
return 0, 0
}
var totalTime int64
var totalWork uint64
var count int
for h := height; h > 0 && count < samples; h-- {
block := c.GetBlockByHeight(h)
Expand All @@ -1409,14 +1410,18 @@ func (c *Chain) RecentBlockStats(samples int) (hashrate float64, avgBlockTime fl
dt := block.Header.Timestamp - prev.Header.Timestamp
if dt > 0 {
totalTime += dt
totalWork += block.Header.Difficulty
count++
}
}
if count == 0 || totalTime == 0 {
return 0, 0
}
avgBlockTime = float64(totalTime) / float64(count)
hashrate = float64(c.NextDifficulty()) / avgBlockTime
// Each sampled interval ended with `block`, so its observed work is that
// block's difficulty. Using the next-block difficulty here biases the
// estimate whenever difficulty changes during the sample window.
hashrate = float64(totalWork) / float64(totalTime)
return hashrate, avgBlockTime
}

Expand Down
48 changes: 48 additions & 0 deletions block_stats_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"math"
"testing"
)

func TestRecentBlockStatsUsesObservedIntervalWork(t *testing.T) {
chain, storage, cleanup := mustCreateTestChain(t)
defer cleanup()
mustAddGenesisBlock(t, chain)

genesis := chain.GetBlockByHeight(0)
prev := genesis
timestamp := genesis.Header.Timestamp
var totalWork uint64
for height, difficulty := range []uint64{100, 300, 500} {
timestamp += int64((height + 1) * 10)
block := &Block{Header: BlockHeader{
Version: 1,
Height: uint64(height + 1),
PrevHash: prev.Hash(),
Timestamp: timestamp,
Difficulty: difficulty,
}}
if err := storage.SaveBlock(block); err != nil {
t.Fatalf("save block %d: %v", height+1, err)
}
if err := storage.SetMainChainBlock(uint64(height+1), block.Hash()); err != nil {
t.Fatalf("index block %d: %v", height+1, err)
}
prev = block
totalWork += difficulty
}

chain.mu.Lock()
chain.height = 3
chain.bestHash = prev.Hash()
chain.mu.Unlock()

hashrate, avgBlockTime := chain.RecentBlockStats(3)
if want := 20.0; math.Abs(avgBlockTime-want) > 1e-9 {
t.Fatalf("average block time = %v, want %v", avgBlockTime, want)
}
if want := float64(totalWork) / 60.0; math.Abs(hashrate-want) > 1e-9 {
t.Fatalf("network hashrate = %v, want observed work/time %v", hashrate, want)
}
}