prysm-pulse/shared/slotutil/slotticker.go
Raul Jordan bb3ee07a3d
Standardize Slot Ticker with params.BeaconConfig().GenesisSlot (#1569)
* tests passing after standardizing to genesis slot

* goimports

* no more magic numbers in current slot

* fmt
2019-02-12 14:58:35 -06:00

95 lines
2.3 KiB
Go

package slotutil
import (
"time"
"github.com/prysmaticlabs/prysm/shared/params"
)
// SlotTicker is a special ticker for the beacon chain block.
// The channel emits over the slot interval, and ensures that
// the ticks are in line with the genesis time. This means that
// the duration between the ticks and the genesis time are always a
// multiple of the slot duration.
// In addition, the channel returns the new slot number.
type SlotTicker struct {
c chan uint64
done chan struct{}
}
// C returns the ticker channel. Call Cancel afterwards to ensure
// that the goroutine exits cleanly.
func (s *SlotTicker) C() <-chan uint64 {
return s.c
}
// Done should be called to clean up the ticker.
func (s *SlotTicker) Done() {
go func() {
s.done <- struct{}{}
}()
}
// GetSlotTicker is the constructor for SlotTicker.
func GetSlotTicker(genesisTime time.Time, slotDuration uint64) *SlotTicker {
ticker := &SlotTicker{
c: make(chan uint64),
done: make(chan struct{}),
}
ticker.start(genesisTime, slotDuration, time.Since, time.Until, time.After)
return ticker
}
// CurrentSlot accepts the genesis time and returns the current time's slot.
func CurrentSlot(
genesisTime time.Time,
slotDuration uint64,
since func(time.Time) time.Duration) uint64 {
sinceGenesis := since(genesisTime)
if sinceGenesis < 0 {
return params.BeaconConfig().GenesisSlot
}
durationInSeconds := time.Duration(slotDuration) * time.Second
return uint64(sinceGenesis/durationInSeconds) + params.BeaconConfig().GenesisSlot
}
func (s *SlotTicker) start(
genesisTime time.Time,
slotDuration uint64,
since func(time.Time) time.Duration,
until func(time.Time) time.Duration,
after func(time.Duration) <-chan time.Time) {
d := time.Duration(slotDuration) * time.Second
go func() {
sinceGenesis := since(genesisTime)
var nextTickTime time.Time
var slot uint64
if sinceGenesis < 0 {
// Handle when the current time is before the genesis time.
nextTickTime = genesisTime
slot = params.BeaconConfig().GenesisSlot
} else {
nextTick := sinceGenesis.Truncate(d) + d
nextTickTime = genesisTime.Add(nextTick)
slot = uint64(nextTick/d) + params.BeaconConfig().GenesisSlot
}
for {
waitTime := until(nextTickTime)
select {
case <-after(waitTime):
s.c <- slot
slot++
nextTickTime = nextTickTime.Add(d)
case <-s.done:
return
}
}
}()
}