This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
/
roughtime.go
68 lines (57 loc) · 1.54 KB
/
roughtime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2017-2019 The Qitmeer developers
//
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package roughtime
import (
"log"
"time"
rt "github.com/cloudflare/roughtime"
)
const RecalibrationInterval = time.Hour
var offset time.Duration
func Init() {
log.Println("Init roughtime... ...")
recalibrateRoughtime()
runT := time.NewTimer(RecalibrationInterval)
go func() {
for {
select {
case <-runT.C:
recalibrateRoughtime()
}
}
}()
}
func recalibrateRoughtime() {
t0 := time.Now()
results := rt.Do(rt.Ecosystem, rt.DefaultQueryAttempts, rt.DefaultQueryTimeout, nil)
// Compute the average difference between the system's time and the
// Roughtime responses from the servers, rejecting responses whose radii
// are larger than 2 seconds.
var err error
offset, err = rt.AvgDeltaWithRadiusThresh(results, t0, 2*time.Second)
if err != nil {
log.Printf("Failed to calculate roughtime offset, system time will be used by default.(%s)", err)
} else {
log.Printf("Roughtime offset:%s", offset)
}
}
// Since returns the duration since t, based on the roughtime response
func Since(t time.Time) time.Duration {
return Now().Sub(t)
}
// Until returns the duration until t, based on the roughtime response
func Until(t time.Time) time.Duration {
return t.Sub(Now())
}
// Now returns the current local time given the roughtime offset.
func Now() time.Time {
if offset <= 0 {
return time.Now()
}
return time.Now().Add(offset)
}
func Offset() time.Duration {
return offset
}