github.com/prysmaticlabs/prysm@v1.4.4/shared/slotutil/countdown.go (about)

     1  package slotutil
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/prysmaticlabs/prysm/shared/params"
     9  	"github.com/prysmaticlabs/prysm/shared/timeutils"
    10  	"github.com/sirupsen/logrus"
    11  )
    12  
    13  var log = logrus.WithField("prefix", "slotutil")
    14  
    15  // CountdownToGenesis starts a ticker at the specified duration
    16  // logging the remaining minutes until the genesis chainstart event
    17  // along with important genesis state metadata such as number
    18  // of genesis validators.
    19  func CountdownToGenesis(ctx context.Context, genesisTime time.Time, genesisValidatorCount uint64, genesisStateRoot [32]byte) {
    20  	ticker := time.NewTicker(params.BeaconConfig().GenesisCountdownInterval)
    21  	defer func() {
    22  		// Used in anonymous function to make sure that updated (per second) ticker is stopped.
    23  		ticker.Stop()
    24  	}()
    25  	logFields := logrus.Fields{
    26  		"genesisValidators": fmt.Sprintf("%d", genesisValidatorCount),
    27  		"genesisTime":       fmt.Sprintf("%v", genesisTime),
    28  		"genesisStateRoot":  fmt.Sprintf("%x", genesisStateRoot),
    29  	}
    30  	secondTimerActivated := false
    31  	for {
    32  		currentTime := timeutils.Now()
    33  		if currentTime.After(genesisTime) {
    34  			log.WithFields(logFields).Info("Chain genesis time reached")
    35  			return
    36  		}
    37  		timeRemaining := genesisTime.Sub(currentTime)
    38  		if !secondTimerActivated && timeRemaining <= 2*time.Minute {
    39  			ticker.Stop()
    40  			// Replace ticker with a one having higher granularity.
    41  			ticker = time.NewTicker(time.Second)
    42  			secondTimerActivated = true
    43  		}
    44  		select {
    45  		case <-ticker.C:
    46  			if timeRemaining >= time.Second {
    47  				log.WithFields(logFields).Infof(
    48  					"%s until chain genesis",
    49  					timeRemaining.Truncate(time.Second),
    50  				)
    51  			}
    52  		case <-ctx.Done():
    53  			log.Debug("Context closed, exiting routine")
    54  			return
    55  		}
    56  	}
    57  }