-
Notifications
You must be signed in to change notification settings - Fork 43
/
p2pcoordinator.go
163 lines (150 loc) · 4.33 KB
/
p2pcoordinator.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"fmt"
"log"
"net"
"time"
)
// Messages to the p2p controller goroutine
const (
p2pCtrlSearchForBlocks = iota
p2pCtrlHaveNewBlock
p2pCtrlConnectPeers
)
type p2pCtrlMessage struct {
msgType int
payload interface{}
}
var p2pCtrlChannel = make(chan p2pCtrlMessage, 8)
// Data related to the (single instance of) the global p2p coordinator. This is also a
// single-threaded object, its fields and methods are only expected to be accessed from
// the Run() goroutine.
type p2pCoordinatorType struct {
timeTicks chan int
lastTickBlockchainHeight int
recentlyRequestedBlocks *StringSetWithExpiry
lastReconnectTime time.Time
badPeers *StringSetWithExpiry
}
// XXX: singletons in go?
var p2pCoordinator = p2pCoordinatorType{
recentlyRequestedBlocks: NewStringSetWithExpiry(5 * time.Second),
lastReconnectTime: time.Now(),
timeTicks: make(chan int),
badPeers: NewStringSetWithExpiry(15 * time.Minute),
}
func (co *p2pCoordinatorType) Run() {
co.lastTickBlockchainHeight = dbGetBlockchainHeight()
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case msg := <-p2pCtrlChannel:
switch msg.msgType {
case p2pCtrlSearchForBlocks:
co.handleSearchForBlocks(msg.payload.(*p2pConnection))
case p2pCtrlConnectPeers:
co.handleConnectPeers(msg.payload.([]string))
}
case <-ticker.C:
co.handleTimeTick()
}
}
}
// Retrieves block hashes from a node which apparently has more blocks than we do.
// ToDo: This is a simplistic version. Make it better by introducing quorums.
func (co *p2pCoordinatorType) handleSearchForBlocks(p2pcStart *p2pConnection) {
msg := p2pMsgGetBlockHashesStruct{
p2pMsgHeader: p2pMsgHeader{
P2pID: p2pEphemeralID,
Root: chainParams.GenesisBlockHash,
Msg: p2pMsgGetBlockHashes,
},
MinBlockHeight: dbGetBlockchainHeight(),
MaxBlockHeight: p2pcStart.chainHeight,
}
log.Printf("Searching for blocks from %d to %d", msg.MinBlockHeight, msg.MaxBlockHeight)
p2pcStart.chanToPeer <- msg
}
func (co *p2pCoordinatorType) handleConnectPeers(addresses []string) {
localAddresses := getLocalAddresses()
for _, address := range addresses {
host, _, err := splitAddress(address)
if err != nil {
log.Println(address, err)
continue
}
canonicalAddress := fmt.Sprintf("%s:%d", host, DefaultP2PPort)
if p2pPeers.HasAddress(canonicalAddress) || co.badPeers.Has(canonicalAddress) {
continue
}
addr, err := net.ResolveTCPAddr("tcp", canonicalAddress)
if err != nil {
continue
}
if inStrings(addr.IP.String(), localAddresses) {
continue
}
// Detect if there's a canonical peer on the other side, somewhat brute-forceish
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
return
}
p2pc, err := p2pSetupPeer(addr.String(), conn)
if err != nil {
log.Println("handleConnectPeers:", err)
continue
}
go p2pc.handleConnection()
log.Println("Detected canonical peer at", canonicalAddress)
dbSavePeer(canonicalAddress)
}
}
// Executed periodically to perform time-dependant actions. Do not rely on the
// time period to be predictable or precise.
func (co *p2pCoordinatorType) handleTimeTick() {
newHeight := dbGetBlockchainHeight()
if newHeight > co.lastTickBlockchainHeight {
log.Println("New blocks detected. New max height:", newHeight)
co.floodPeersWithNewBlocks(co.lastTickBlockchainHeight, newHeight)
co.lastTickBlockchainHeight = newHeight
}
if time.Since(co.lastReconnectTime) >= 10*time.Minute {
co.lastReconnectTime = time.Now()
p2pPeers.saveConnectablePeers()
co.connectDbPeers()
}
p2pPeers.tryPeersConnectable()
}
func (co *p2pCoordinatorType) floodPeersWithNewBlocks(minHeight, maxHeight int) {
blockHashes := dbGetHeightHashes(minHeight, maxHeight)
msg := p2pMsgBlockHashesStruct{
p2pMsgHeader: p2pMsgHeader{
P2pID: p2pEphemeralID,
Root: chainParams.GenesisBlockHash,
Msg: p2pMsgBlockHashes,
},
Hashes: blockHashes,
}
p2pPeers.lock.With(func() {
for p2pc := range p2pPeers.peers {
p2pc.chanToPeer <- msg
}
})
}
func (co *p2pCoordinatorType) connectDbPeers() {
peers := dbGetSavedPeers()
for peer := range peers {
if p2pPeers.HasAddress(peer) {
continue
}
if co.badPeers.Has(peer) {
continue
}
p2pc, err := p2pConnectPeer(peer)
if err != nil {
continue
}
go p2pc.handleConnection()
}
}