Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

Commit

Permalink
Move block height estimation to its own function and test it
Browse files Browse the repository at this point in the history
  • Loading branch information
VoidingWarranties committed May 25, 2016
1 parent 586a045 commit f2ed3ca
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 6 deletions.
19 changes: 13 additions & 6 deletions siac/consensuscmd.go
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/spf13/cobra"

"github.com/NebulousLabs/Sia/api"
"github.com/NebulousLabs/Sia/types"
)

var (
Expand All @@ -33,15 +34,21 @@ Height: %v
Target: %v
`, yesNo(cg.Synced), cg.CurrentBlock, cg.Height, cg.Target)
} else {
// Estimate the height of the blockchain by calculating the minutes since a
// known block, and dividing by 10 minutes (the block time).
block50000Timestamp := time.Date(2016, time.May, 11, 19, 33, 0, 0, time.UTC)
diff := time.Since(block50000Timestamp)
estimatedHeight := 50000 + (diff.Minutes() / 10)
estimatedProgress := float64(cg.Height) / estimatedHeight * 100
estimatedHeight := estimatedHeightAt(time.Now())
estimatedProgress := float64(cg.Height) / float64(estimatedHeight) * 100
fmt.Printf(`Synced: %v
Height: %v
Progress (estimated): %.f%%
`, yesNo(cg.Synced), cg.Height, estimatedProgress)
}
}

// estimatedHeightAt returns the estimated block height for the given time.
// Block height is estimated by calculating the minutes since a known block in
// the past and dividing by 10 minutes (the block time).
func estimatedHeightAt(t time.Time) types.BlockHeight {
block5e4Timestamp := time.Date(2016, time.May, 11, 19, 33, 0, 0, time.UTC)
diff := t.Sub(block5e4Timestamp)
estimatedHeight := 5e4 + (diff.Minutes() / 10)
return types.BlockHeight(estimatedHeight + 0.5) // round to the nearest block
}
49 changes: 49 additions & 0 deletions siac/consensuscmd_test.go
@@ -0,0 +1,49 @@
package main

import (
"testing"
"time"

"github.com/NebulousLabs/Sia/types"
)

// TestEstimatedHeightAt tests that the expectedHeightAt function correctly
// estimates the blockheight (and rounds to the nearest block).
func TestEstimatedHeightAt(t *testing.T) {
tests := []struct {
t time.Time
expectedHeight types.BlockHeight
}{
// Test on the same block that is used to estimate the height
{
time.Date(2016, time.May, 11, 19, 33, 0, 0, time.UTC),
5e4,
},
// 4 minutes later
{
time.Date(2016, time.May, 11, 19, 37, 0, 0, time.UTC),
5e4,
},
// 5 minutes later
{
time.Date(2016, time.May, 11, 19, 38, 0, 0, time.UTC),
5e4 + 1,
},
// 10 minutes later
{
time.Date(2016, time.May, 11, 19, 43, 0, 0, time.UTC),
5e4 + 1,
},
// 1 day later
{
time.Date(2016, time.May, 12, 19, 33, 0, 0, time.UTC),
5e4 + 144,
},
}
for _, tt := range tests {
h := estimatedHeightAt(tt.t)
if h != tt.expectedHeight {
t.Errorf("expected an estimated height of %v, but got %v", tt.expectedHeight, h)
}
}
}

0 comments on commit f2ed3ca

Please sign in to comment.