1 // Copyright (c) 2013-2014 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
15 // maxAllowedOffsetSeconds is the maximum number of seconds in either
16 // direction that local clock will be adjusted. When the median time
17 // of the network is outside of this range, no offset will be applied.
18 maxAllowedOffsetSecs = 70 * 60 // 1 hour 10 minutes
20 // similarTimeSecs is the number of seconds in either direction from the
21 // local clock that is used to determine that it is likley wrong and
22 // hence to show a warning.
23 similarTimeSecs = 5 * 60 // 5 minutes
27 // maxMedianTimeEntries is the maximum number of entries allowed in the
28 // median time data. This is a variable as opposed to a constant so the
29 // test code can modify it.
30 maxMedianTimeEntries = 200
33 // MedianTimeSource provides a mechanism to add several time samples which are
34 // used to determine a median time which is then used as an offset to the local
36 type MedianTimeSource interface {
37 // AdjustedTime returns the current time adjusted by the median time
38 // offset as calculated from the time samples added by AddTimeSample.
39 AdjustedTime() time.Time
41 // AddTimeSample adds a time sample that is used when determining the
42 // median time of the added samples.
43 AddTimeSample(id string, timeVal time.Time)
45 // Offset returns the number of seconds to adjust the local clock based
46 // upon the median of the time samples added by AddTimeData.
47 Offset() time.Duration
50 // int64Sorter implements sort.Interface to allow a slice of 64-bit integers to
52 type int64Sorter []int64
54 // Len returns the number of 64-bit integers in the slice. It is part of the
55 // sort.Interface implementation.
56 func (s int64Sorter) Len() int {
60 // Swap swaps the 64-bit integers at the passed indices. It is part of the
61 // sort.Interface implementation.
62 func (s int64Sorter) Swap(i, j int) {
63 s[i], s[j] = s[j], s[i]
66 // Less returns whether the 64-bit integer with index i should sort before the
67 // 64-bit integer with index j. It is part of the sort.Interface
69 func (s int64Sorter) Less(i, j int) bool {
73 // medianTime provides an implementation of the MedianTimeSource interface.
74 // It is limited to maxMedianTimeEntries includes the same buggy behavior as
75 // the time offset mechanism in Bitcoin Core. This is necessary because it is
76 // used in the consensus code.
77 type medianTime struct {
79 knownIDs map[string]struct{}
82 invalidTimeChecked bool
85 // Ensure the medianTime type implements the MedianTimeSource interface.
86 var _ MedianTimeSource = (*medianTime)(nil)
88 // AdjustedTime returns the current time adjusted by the median time offset as
89 // calculated from the time samples added by AddTimeSample.
91 // This function is safe for concurrent access and is part of the
92 // MedianTimeSource interface implementation.
93 func (m *medianTime) AdjustedTime() time.Time {
97 // Limit the adjusted time to 1 second precision.
98 now := time.Unix(time.Now().Unix(), 0)
99 return now.Add(time.Duration(m.offsetSecs) * time.Second)
102 // AddTimeSample adds a time sample that is used when determining the median
103 // time of the added samples.
105 // This function is safe for concurrent access and is part of the
106 // MedianTimeSource interface implementation.
107 func (m *medianTime) AddTimeSample(sourceID string, timeVal time.Time) {
111 // Don't add time data from the same source.
112 if _, exists := m.knownIDs[sourceID]; exists {
115 m.knownIDs[sourceID] = struct{}{}
117 // Truncate the provided offset to seconds and append it to the slice
118 // of offsets while respecting the maximum number of allowed entries by
119 // replacing the oldest entry with the new entry once the maximum number
120 // of entries is reached.
121 now := time.Unix(time.Now().Unix(), 0)
122 offsetSecs := int64(timeVal.Sub(now).Seconds())
123 numOffsets := len(m.offsets)
124 if numOffsets == maxMedianTimeEntries && maxMedianTimeEntries > 0 {
125 m.offsets = m.offsets[1:]
128 m.offsets = append(m.offsets, offsetSecs)
131 // Sort the offsets so the median can be obtained as needed later.
132 sortedOffsets := make([]int64, numOffsets)
133 copy(sortedOffsets, m.offsets)
134 sort.Sort(int64Sorter(sortedOffsets))
136 offsetDuration := time.Duration(offsetSecs) * time.Second
137 log.Debugf("Added time sample of %v (total: %v)", offsetDuration,
140 // NOTE: The following code intentionally has a bug to mirror the
141 // buggy behavior in Bitcoin Core since the median time is used in the
144 // In particular, the offset is only updated when the number of entries
145 // is odd, but the max number of entries is 200, an even number. Thus,
146 // the offset will never be updated again once the max number of entries
149 // The median offset is only updated when there are enough offsets and
150 // the number of offsets is odd so the middle value is the true median.
151 // Thus, there is nothing to do when those conditions are not met.
152 if numOffsets < 5 || numOffsets&0x01 != 1 {
156 // At this point the number of offsets in the list is odd, so the
157 // middle value of the sorted offsets is the median.
158 median := sortedOffsets[numOffsets/2]
160 // Set the new offset when the median offset is within the allowed
162 if math.Abs(float64(median)) < maxAllowedOffsetSecs {
163 m.offsetSecs = median
165 // The median offset of all added time data is larger than the
166 // maximum allowed offset, so don't use an offset. This
167 // effectively limits how far the local clock can be skewed.
170 if !m.invalidTimeChecked {
171 m.invalidTimeChecked = true
173 // Find if any time samples have a time that is close
174 // to the local time.
175 var remoteHasCloseTime bool
176 for _, offset := range sortedOffsets {
177 if math.Abs(float64(offset)) < similarTimeSecs {
178 remoteHasCloseTime = true
183 // Warn if none of the time samples are close.
184 if !remoteHasCloseTime {
185 log.Warnf("Please check your date and time " +
186 "are correct! btcd will not work " +
187 "properly with an invalid time")
192 medianDuration := time.Duration(m.offsetSecs) * time.Second
193 log.Debugf("New time offset: %v", medianDuration)
196 // Offset returns the number of seconds to adjust the local clock based upon the
197 // median of the time samples added by AddTimeData.
199 // This function is safe for concurrent access and is part of the
200 // MedianTimeSource interface implementation.
201 func (m *medianTime) Offset() time.Duration {
205 return time.Duration(m.offsetSecs) * time.Second
208 // NewMedianTime returns a new instance of concurrency-safe implementation of
209 // the MedianTimeSource interface. The returned implementation contains the
210 // rules necessary for proper time handling in the chain consensus rules and
211 // expects the time samples to be added from the timestamp field of the version
212 // message received from remote peers that successfully connect and negotiate.
213 func NewMedianTime() MedianTimeSource {
215 knownIDs: make(map[string]struct{}),
216 offsets: make([]int64, 0, maxMedianTimeEntries),