/
protocol.go
353 lines (300 loc) · 8.97 KB
/
protocol.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package selection
import (
"bytes"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/loveandpeople-DAG/goHive/autopeering/peer"
"github.com/loveandpeople-DAG/goHive/autopeering/salt"
pb "github.com/loveandpeople-DAG/goHive/autopeering/selection/proto"
"github.com/loveandpeople-DAG/goHive/autopeering/server"
"github.com/loveandpeople-DAG/goHive/backoff"
"github.com/loveandpeople-DAG/goHive/identity"
"github.com/loveandpeople-DAG/goHive/logger"
"github.com/loveandpeople-DAG/goHive/typeutils"
"google.golang.org/protobuf/proto"
)
const (
maxRetries = 2
logSends = true
)
// policy for retrying failed network calls
var retryPolicy = backoff.ExponentialBackOff(500*time.Millisecond, 1.5).With(
backoff.Jitter(0.5), backoff.MaxRetries(maxRetries))
// DiscoverProtocol specifies the methods from the peer discovery that are required.
type DiscoverProtocol interface {
IsVerified(identity.ID, net.IP) bool
EnsureVerified(*peer.Peer) error
GetVerifiedPeer(identity.ID) *peer.Peer
GetVerifiedPeers() []*peer.Peer
}
// The Protocol handles the neighbor selection.
// It responds to incoming messages and sends own requests when needed.
type Protocol struct {
server.Protocol
disc DiscoverProtocol // reference to the peer discovery to query verified peers
loc *peer.Local // local peer that runs the protocol
log *logger.Logger // logging
mgr *manager // the manager handles the actual neighbor selection
running *typeutils.AtomicBool
closeOnce sync.Once
}
// New creates a new neighbor selection protocol.
func New(local *peer.Local, disc DiscoverProtocol, opts ...Option) *Protocol {
args := &options{
log: logger.NewNopLogger(),
dropOnUpdate: false,
neighborValidator: nil,
}
for _, opt := range opts {
opt.apply(args)
}
p := &Protocol{
Protocol: server.Protocol{},
loc: local,
disc: disc,
log: args.log,
running: typeutils.NewAtomicBool(),
}
p.mgr = newManager(p, disc.GetVerifiedPeers, args.log.Named("mgr"), args)
return p
}
// Start starts the actual neighbor selection over the provided Sender.
func (p *Protocol) Start(s server.Sender) {
p.Protocol.Sender = s
p.mgr.start()
p.log.Debug("neighborhood started")
p.running.Set()
}
// Close finalizes the protocol.
func (p *Protocol) Close() {
p.closeOnce.Do(func() {
p.running.UnSet()
p.mgr.close()
})
}
// Events returns all the events that are triggered during the neighbor selection.
func (p *Protocol) Events() Events {
return p.mgr.events
}
// GetNeighbors returns the current neighbors.
func (p *Protocol) GetNeighbors() []*peer.Peer {
return p.mgr.getNeighbors()
}
// GetIncomingNeighbors returns the current incoming neighbors.
func (p *Protocol) GetIncomingNeighbors() []*peer.Peer {
return p.mgr.getInNeighbors()
}
// GetOutgoingNeighbors returns the current outgoing neighbors.
func (p *Protocol) GetOutgoingNeighbors() []*peer.Peer {
return p.mgr.getOutNeighbors()
}
// RemoveNeighbor removes the peer with the given id from the incoming and outgoing neighbors.
// If such a peer was actually contained in anyone of the neighbor sets, the corresponding event is triggered
// and the corresponding peering drop is sent. Otherwise the call is ignored.
func (p *Protocol) RemoveNeighbor(id identity.ID) {
p.mgr.removeNeighbor(id)
}
// HandleMessage responds to incoming neighbor selection messages.
func (p *Protocol) HandleMessage(s *server.Server, fromAddr *net.UDPAddr, from *identity.Identity, data []byte) (bool, error) {
if !p.running.IsSet() {
return false, nil
}
switch pb.MType(data[0]) {
// PeeringRequest
case pb.MPeeringRequest:
m := new(pb.PeeringRequest)
if err := proto.Unmarshal(data[1:], m); err != nil {
return true, fmt.Errorf("invalid message: %w", err)
}
if p.validatePeeringRequest(fromAddr, from.ID(), m) {
p.handlePeeringRequest(s, from.ID(), data, m)
}
// PeeringResponse
case pb.MPeeringResponse:
m := new(pb.PeeringResponse)
if err := proto.Unmarshal(data[1:], m); err != nil {
return true, fmt.Errorf("invalid message: %w", err)
}
p.validatePeeringResponse(s, fromAddr, from.ID(), m)
// PeeringResponse messages are handled in the handleReply function of the validation
// PeeringDrop
case pb.MPeeringDrop:
m := new(pb.PeeringDrop)
if err := proto.Unmarshal(data[1:], m); err != nil {
return true, fmt.Errorf("invalid message: %w", err)
}
if p.validatePeeringDrop(fromAddr, m) {
p.handlePeeringDrop(from.ID())
}
default:
return false, nil
}
return true, nil
}
// Local returns the associated local peer of the neighbor selection.
func (p *Protocol) local() *peer.Local {
return p.loc
}
// ------ message senders ------
// PeeringRequest sends a PeeringRequest to the given peer. This method blocks
// until a response is received and the status answer is returned.
func (p *Protocol) PeeringRequest(to *peer.Peer, salt *salt.Salt) (bool, error) {
if err := p.disc.EnsureVerified(to); err != nil {
return false, err
}
// create the request package
toAddr := to.Address()
req := newPeeringRequest(salt)
data := marshal(req)
// compute the message hash
hash := server.PacketHash(data)
var status bool
callback := func(m server.Message) bool {
res := m.(*pb.PeeringResponse)
if !bytes.Equal(res.GetReqHash(), hash) {
return false
}
status = res.GetStatus()
return true
}
err := backoff.Retry(retryPolicy, func() error {
p.logSend(toAddr, req)
err := <-p.Protocol.SendExpectingReply(toAddr, to.ID(), data, pb.MPeeringResponse, callback)
if err != nil && !errors.Is(err, server.ErrTimeout) {
return backoff.Permanent(err)
}
return err
})
return status, err
}
// PeeringDrop sends a peering drop message to the given peer, non-blocking and does not wait for any responses.
func (p *Protocol) PeeringDrop(to *peer.Peer) {
drop := newPeeringDrop()
p.logSend(to.Address(), drop)
p.Protocol.Send(to, marshal(drop))
}
// ------ helper functions ------
func (p *Protocol) logSend(toAddr *net.UDPAddr, msg pb.Message) {
if logSends {
p.log.Debugw("send message", "type", msg.Name(), "addr", toAddr)
}
}
func marshal(msg pb.Message) []byte {
mType := msg.Type()
if mType > 0xFF {
panic("invalid message")
}
data, err := proto.Marshal(msg)
if err != nil {
panic("invalid message")
}
return append([]byte{byte(mType)}, data...)
}
// ------ Message Constructors ------
func newPeeringRequest(salt *salt.Salt) *pb.PeeringRequest {
return &pb.PeeringRequest{
Timestamp: time.Now().Unix(),
Salt: salt.ToProto(),
}
}
func newPeeringResponse(reqData []byte, status bool) *pb.PeeringResponse {
return &pb.PeeringResponse{
ReqHash: server.PacketHash(reqData),
Status: status,
}
}
func newPeeringDrop() *pb.PeeringDrop {
return &pb.PeeringDrop{
Timestamp: time.Now().Unix(),
}
}
// ------ Packet Handlers ------
func (p *Protocol) validatePeeringRequest(fromAddr *net.UDPAddr, fromID identity.ID, m *pb.PeeringRequest) bool {
// check Timestamp
if p.Protocol.IsExpired(m.GetTimestamp()) {
p.log.Debugw("invalid message",
"type", m.Name(),
"timestamp", time.Unix(m.GetTimestamp(), 0),
)
return false
}
// check whether the sender is verified
if !p.disc.IsVerified(fromID, fromAddr.IP) {
p.log.Debugw("invalid message",
"type", m.Name(),
"unverified", fromAddr,
)
return false
}
// check Salt
s, err := salt.FromProto(m.GetSalt())
if err != nil {
p.log.Debugw("invalid message",
"type", m.Name(),
"salt", err,
)
return false
}
// check salt expiration
if s.Expired() {
p.log.Debugw("invalid message",
"type", m.Name(),
"salt.expiration", s.GetExpiration(),
)
return false
}
p.log.Debugw("valid message",
"type", m.Name(),
"addr", fromAddr,
)
return true
}
func (p *Protocol) handlePeeringRequest(s *server.Server, fromID identity.ID, rawData []byte, m *pb.PeeringRequest) {
fromSalt, err := salt.FromProto(m.GetSalt())
if err != nil {
// this should not happen as it is checked in validation
p.log.Warnw("invalid salt", "err", err)
return
}
from := p.disc.GetVerifiedPeer(fromID)
status := p.mgr.requestPeering(from, fromSalt)
res := newPeeringResponse(rawData, status)
p.logSend(from.Address(), res)
s.Send(from.Address(), marshal(res))
}
func (p *Protocol) validatePeeringResponse(s *server.Server, fromAddr *net.UDPAddr, fromID identity.ID, m *pb.PeeringResponse) bool {
// there must be a request waiting for this response
if !s.IsExpectedReply(fromAddr.IP, fromID, m) {
p.log.Debugw("invalid message",
"type", m.Name(),
"unexpected", fromAddr,
)
return false
}
p.log.Debugw("valid message",
"type", m.Name(),
"addr", fromAddr,
)
return true
}
func (p *Protocol) validatePeeringDrop(fromAddr *net.UDPAddr, m *pb.PeeringDrop) bool {
// check Timestamp
if p.Protocol.IsExpired(m.GetTimestamp()) {
p.log.Debugw("invalid message",
"type", m.Name(),
"timestamp", time.Unix(m.GetTimestamp(), 0),
)
return false
}
p.log.Debugw("valid message",
"type", m.Name(),
"addr", fromAddr,
)
return true
}
func (p *Protocol) handlePeeringDrop(fromID identity.ID) {
p.mgr.removeNeighbor(fromID)
}