github.com/annchain/OG@v0.0.9/p2p/discv5/ntp.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Contains the NTP time drift detection via the SNTP protocol:
    18  //   https://tools.ietf.org/html/rfc4330
    19  
    20  package discv5
    21  
    22  import (
    23  	"fmt"
    24  	"net"
    25  	"sort"
    26  	"strings"
    27  	"time"
    28  )
    29  
    30  const (
    31  	ntpPool   = "pool.ntp.org" // ntpPool is the NTP server to query for the current time
    32  	ntpChecks = 3              // Number of measurements to do against the NTP server
    33  )
    34  
    35  // durationSlice attaches the methods of sort.Interface to []time.Duration,
    36  // sorting in increasing order.
    37  type durationSlice []time.Duration
    38  
    39  func (s durationSlice) Len() int           { return len(s) }
    40  func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
    41  func (s durationSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    42  
    43  // checkClockDrift queries an NTP server for clock drifts and warns the user if
    44  // one large enough is detected.
    45  func checkClockDrift() {
    46  	drift, err := sntpDrift(ntpChecks)
    47  	if err != nil {
    48  		return
    49  	}
    50  	if drift < -driftThreshold || drift > driftThreshold {
    51  		warning := fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift)
    52  		howtofix := fmt.Sprintf("Please enable network time synchronisation in system settings")
    53  		separator := strings.Repeat("-", len(warning))
    54  
    55  		log.Warn(separator)
    56  		log.Warn(warning)
    57  		log.Warn(howtofix)
    58  		log.Warn(separator)
    59  	} else {
    60  		log.Debug(fmt.Sprintf("Sanity NTP check reported %v drift, all ok", drift))
    61  	}
    62  }
    63  
    64  // sntpDrift does a naive time resolution against an NTP server and returns the
    65  // measured drift. This method uses the simple version of NTP. It's not precise
    66  // but should be fine for these purposes.
    67  //
    68  // Note, it executes two extra measurements compared to the number of requested
    69  // ones to be able to discard the two extremes as outliers.
    70  func sntpDrift(measurements int) (time.Duration, error) {
    71  	// Resolve the address of the NTP server
    72  	addr, err := net.ResolveUDPAddr("udp", ntpPool+":123")
    73  	if err != nil {
    74  		return 0, err
    75  	}
    76  	// Construct the time request (empty package with only 2 fields set):
    77  	//   Bits 3-5: Protocol version, 3
    78  	//   Bits 6-8: Mode of operation, client, 3
    79  	request := make([]byte, 48)
    80  	request[0] = 3<<3 | 3
    81  
    82  	// Execute each of the measurements
    83  	drifts := []time.Duration{}
    84  	for i := 0; i < measurements+2; i++ {
    85  		// Dial the NTP server and send the time retrieval request
    86  		conn, err := net.DialUDP("udp", nil, addr)
    87  		if err != nil {
    88  			return 0, err
    89  		}
    90  		defer conn.Close()
    91  
    92  		sent := time.Now()
    93  		if _, err = conn.Write(request); err != nil {
    94  			return 0, err
    95  		}
    96  		// Retrieve the reply and calculate the elapsed time
    97  		conn.SetDeadline(time.Now().Add(5 * time.Second))
    98  
    99  		reply := make([]byte, 48)
   100  		if _, err = conn.Read(reply); err != nil {
   101  			return 0, err
   102  		}
   103  		elapsed := time.Since(sent)
   104  
   105  		// Reconstruct the time from the reply data
   106  		sec := uint64(reply[43]) | uint64(reply[42])<<8 | uint64(reply[41])<<16 | uint64(reply[40])<<24
   107  		frac := uint64(reply[47]) | uint64(reply[46])<<8 | uint64(reply[45])<<16 | uint64(reply[44])<<24
   108  
   109  		nanosec := sec*1e9 + (frac*1e9)>>32
   110  
   111  		t := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nanosec)).Local()
   112  
   113  		// Calculate the drift based on an assumed answer time of RRT/2
   114  		drifts = append(drifts, sent.Sub(t)+elapsed/2)
   115  	}
   116  	// Calculate average drif (drop two extremities to avoid outliers)
   117  	sort.Sort(durationSlice(drifts))
   118  
   119  	drift := time.Duration(0)
   120  	for i := 1; i < len(drifts)-1; i++ {
   121  		drift += drifts[i]
   122  	}
   123  	return drift / time.Duration(measurements), nil
   124  }