-
Notifications
You must be signed in to change notification settings - Fork 1
/
block.go
76 lines (62 loc) · 1.22 KB
/
block.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
69
70
71
72
73
74
75
76
package common
import (
"fmt"
"log"
"time"
)
type BlockTrack struct {
previous uint64
current uint64
currentTime time.Time
}
func (b *BlockTrack) canAdd(blockNum uint64) bool {
if blockNum == 0 {
return false
}
if b.current == blockNum {
// seen already
return false
}
return true
}
func (b *BlockTrack) checkDistance() {
if b.previous == 0 {
return
}
distance := b.current - b.previous
if distance > 1 {
log.Printf("block track distance %d: %d > %d\n", distance, b.previous, b.current)
}
}
func (b *BlockTrack) AddBlock(blockNum uint64) {
if !b.canAdd(blockNum) {
return
}
// store previous
b.previous = b.current
// add block
b.current = blockNum
b.currentTime = time.Now()
b.checkDistance()
}
func (b *BlockTrack) HealthCheck() error {
if !b.isHealthy() {
return fmt.Errorf("waiting for new blocks, latest %d", b.current)
}
return nil
}
func (b *BlockTrack) isHealthy() bool {
// no block info yet
if b.current == 0 || b.previous == 0 {
return false
}
// difference is too high, let's wait for a new block
if b.current-b.previous > 10 {
return false
}
// the last block was added long time ago
if time.Since(b.currentTime).Minutes() > 5 {
return false
}
return true
}