Skip to content

Commit

Permalink
Potential rounding issues (and updating comments) (#742)
Browse files Browse the repository at this point in the history
* Update commets
* Update TimeOfRound

Signed-off-by: Kirk Baird <baird.k@outlook.com>
Co-authored-by: Will <will@cypherpunk.email>
  • Loading branch information
kirk-baird and willscott committed Oct 1, 2020
1 parent 9b1bdef commit 5b9a55a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
9 changes: 6 additions & 3 deletions chain/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@ func TimeOfRound(period time.Duration, genesis int64, round uint64) int64 {
if round == 0 {
return genesis
}
if period < 0 {
return TimeOfRoundErrorValue
}

periodBits := math.Log2(float64(period))
if round > (math.MaxUint64 >> int(periodBits)) {
periodBits := math.Log2(float64(period.Seconds()) + 1) // require x >=1 in log2(x)
if round >= (math.MaxUint64 >> (int(periodBits) + 2)) { // +1 for mul overflow, +1 for casting int64
return TimeOfRoundErrorValue
}
// - 1 because genesis time is for 1st round already
delta := (round - 1) * uint64(period.Seconds())

// - 1 because genesis time is for 1st round already
val := genesis + int64(delta)
if val > math.MaxInt64-maxTimeBuffer {
return TimeOfRoundErrorValue
Expand Down
16 changes: 13 additions & 3 deletions chain/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,19 @@ func TestTimeOverflow(t *testing.T) {
t.Fatal("future rounds should not allow previous times.")
}

overflowRound := TimeOfRound(period, start, math.MaxInt64)
if overflowRound < smallRound {
t.Fatal("future rounds should not allow previous times.")
overflowRound := TimeOfRound(period, start, math.MaxUint64 >> 3)
if overflowRound != TimeOfRoundErrorValue {
t.Fatal("overflow shoud return error.")
}

overflowRound2 := TimeOfRound(period + 2 * time.Second, start, (math.MaxUint64 >> 3) - 1)
if overflowRound2 != TimeOfRoundErrorValue {
t.Fatal("overflow shoud return error.")
}

negativePeriod := TimeOfRound(-1, start, math.MaxUint64)
if negativePeriod != TimeOfRoundErrorValue {
t.Fatal("negative period shoud return error.")
}
}

Expand Down
2 changes: 1 addition & 1 deletion net/control.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type ControlListener struct {
lis net.Listener
}

// NewTCPGrpcControlListener registers the pairing between a ControlServer and a grpx server
// NewTCPGrpcControlListener registers the pairing between a ControlServer and a grpc server
func NewTCPGrpcControlListener(s control.ControlServer, controlAddr string) ControlListener {
lis, err := net.Listen(controlListenAddr(controlAddr))
if err != nil {
Expand Down

0 comments on commit 5b9a55a

Please sign in to comment.