github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/p2p/discover/ntp.go (about)

     1  // Contains the NTP time drift detection via the SNTP protocol:
     2  //   https://tools.ietf.org/html/rfc4330
     3  
     4  package discover
     5  
     6  import (
     7  	"fmt"
     8  	"net"
     9  	"sort"
    10  	"time"
    11  
    12  	"github.com/quickchainproject/quickchain/log"
    13  )
    14  
    15  const (
    16  	ntpPool   = "pool.ntp.org" // ntpPool is the NTP server to query for the current time
    17  	ntpChecks = 3              // Number of measurements to do against the NTP server
    18  )
    19  
    20  // durationSlice attaches the methods of sort.Interface to []time.Duration,
    21  // sorting in increasing order.
    22  type durationSlice []time.Duration
    23  
    24  func (s durationSlice) Len() int           { return len(s) }
    25  func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
    26  func (s durationSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    27  
    28  // checkClockDrift queries an NTP server for clock drifts and warns the user if
    29  // one large enough is detected.
    30  func checkClockDrift() {
    31  	drift, err := sntpDrift(ntpChecks)
    32  	if err != nil {
    33  		return
    34  	}
    35  	if drift < -driftThreshold || drift > driftThreshold {
    36  		log.Warn(fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift))
    37  		log.Warn("Please enable network time synchronisation in system settings.")
    38  	} else {
    39  		log.Debug("NTP sanity check done", "drift", drift)
    40  	}
    41  }
    42  
    43  // sntpDrift does a naive time resolution against an NTP server and returns the
    44  // measured drift. This method uses the simple version of NTP. It's not precise
    45  // but should be fine for these purposes.
    46  //
    47  // Note, it executes two extra measurements compared to the number of requested
    48  // ones to be able to discard the two extremes as outliers.
    49  func sntpDrift(measurements int) (time.Duration, error) {
    50  	// Resolve the address of the NTP server
    51  	addr, err := net.ResolveUDPAddr("udp", ntpPool+":123")
    52  	if err != nil {
    53  		return 0, err
    54  	}
    55  	// Construct the time request (empty package with only 2 fields set):
    56  	//   Bits 3-5: Protocol version, 3
    57  	//   Bits 6-8: Mode of operation, client, 3
    58  	request := make([]byte, 48)
    59  	request[0] = 3<<3 | 3
    60  
    61  	// Execute each of the measurements
    62  	drifts := []time.Duration{}
    63  	for i := 0; i < measurements+2; i++ {
    64  		// Dial the NTP server and send the time retrieval request
    65  		conn, err := net.DialUDP("udp", nil, addr)
    66  		if err != nil {
    67  			return 0, err
    68  		}
    69  		defer conn.Close()
    70  
    71  		sent := time.Now()
    72  		if _, err = conn.Write(request); err != nil {
    73  			return 0, err
    74  		}
    75  		// Retrieve the reply and calculate the elapsed time
    76  		conn.SetDeadline(time.Now().Add(5 * time.Second))
    77  
    78  		reply := make([]byte, 48)
    79  		if _, err = conn.Read(reply); err != nil {
    80  			return 0, err
    81  		}
    82  		elapsed := time.Since(sent)
    83  
    84  		// Reconstruct the time from the reply data
    85  		sec := uint64(reply[43]) | uint64(reply[42])<<8 | uint64(reply[41])<<16 | uint64(reply[40])<<24
    86  		frac := uint64(reply[47]) | uint64(reply[46])<<8 | uint64(reply[45])<<16 | uint64(reply[44])<<24
    87  
    88  		nanosec := sec*1e9 + (frac*1e9)>>32
    89  
    90  		t := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nanosec)).Local()
    91  
    92  		// Calculate the drift based on an assumed answer time of RRT/2
    93  		drifts = append(drifts, sent.Sub(t)+elapsed/2)
    94  	}
    95  	// Calculate average drif (drop two extremities to avoid outliers)
    96  	sort.Sort(durationSlice(drifts))
    97  
    98  	drift := time.Duration(0)
    99  	for i := 1; i < len(drifts)-1; i++ {
   100  		drift += drifts[i]
   101  	}
   102  	return drift / time.Duration(measurements), nil
   103  }