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