-
Notifications
You must be signed in to change notification settings - Fork 109
/
time.go
63 lines (55 loc) 路 2.05 KB
/
time.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
package common
import (
"math"
"time"
)
// time.Unix will add `time.unixToInternal` to a unix timestamp in int64 space.
// TimeOfRound will stay below this buffer so that such a conversion does not overflow.
const timeBufferBits = 36
const maxTimeBuffer = int64(1 << timeBufferBits)
// TimeOfRoundErrorValue is the value returned by `TimeOfRound` when an invalid round is
// specified.
const TimeOfRoundErrorValue = math.MaxInt64 - maxTimeBuffer
// TimeOfRound is returning the time the current round should happen
func TimeOfRound(period time.Duration, genesis int64, round uint64) int64 {
if round == 0 {
return genesis
}
if period < 0 {
return TimeOfRoundErrorValue
}
periodBits := math.Log2(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())
val := genesis + int64(delta)
if val > math.MaxInt64-maxTimeBuffer {
return TimeOfRoundErrorValue
}
return val
}
// CurrentRound calculates the active round at `now`
func CurrentRound(now int64, period time.Duration, genesis int64) uint64 {
nextRound, _ := NextRound(now, period, genesis)
if nextRound <= 1 {
return nextRound
}
return nextRound - 1
}
// NextRound returns the next upcoming round and its UNIX time given the genesis
// time and the period.
// round at time genesis = round 1. Round 0 is fixed.
func NextRound(now int64, period time.Duration, genesis int64) (nextRound uint64, nextTime int64) {
if now < genesis {
return 1, genesis
}
fromGenesis := now - genesis
// we take the time from genesis divided by the periods in seconds, that
// gives us the number of periods since genesis. We add +1 since we want the
// next round. We also add +1 because round 1 starts at genesis time.
nextRound = uint64(math.Floor(float64(fromGenesis)/period.Seconds())) + 1
nextTime = genesis + int64(nextRound*uint64(period.Seconds()))
return nextRound + 1, nextTime
}