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