-
Notifications
You must be signed in to change notification settings - Fork 340
/
handshake.go
355 lines (294 loc) · 10.7 KB
/
handshake.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
354
355
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package handshake
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/ethersphere/bee/pkg/bzz"
"github.com/ethersphere/bee/pkg/crypto"
"github.com/ethersphere/bee/pkg/logging"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/p2p/libp2p/internal/handshake/pb"
"github.com/ethersphere/bee/pkg/p2p/protobuf"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/libp2p/go-libp2p-core/network"
libp2ppeer "github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
)
const (
// ProtocolName is the text of the name of the handshake protocol.
ProtocolName = "handshake"
// ProtocolVersion is the current handshake protocol version.
ProtocolVersion = "4.0.0"
// StreamName is the name of the stream used for handshake purposes.
StreamName = "handshake"
// MaxWelcomeMessageLength is maximum number of characters allowed in the welcome message.
MaxWelcomeMessageLength = 140
handshakeTimeout = 15 * time.Second
)
var (
// ErrNetworkIDIncompatible is returned if response from the other peer does not have valid networkID.
ErrNetworkIDIncompatible = errors.New("incompatible network ID")
// ErrHandshakeDuplicate is returned if the handshake response has been received by an already processed peer.
ErrHandshakeDuplicate = errors.New("duplicate handshake")
// ErrInvalidAck is returned if data in received in ack is not valid (invalid signature for example).
ErrInvalidAck = errors.New("invalid ack")
// ErrInvalidSyn is returned if observable address in ack is not a valid..
ErrInvalidSyn = errors.New("invalid syn")
// ErrWelcomeMessageLength is returned if the welcome message is longer than the maximum length
ErrWelcomeMessageLength = fmt.Errorf("handshake welcome message longer than maximum of %d characters", MaxWelcomeMessageLength)
)
// AdvertisableAddressResolver can Resolve a Multiaddress.
type AdvertisableAddressResolver interface {
Resolve(observedAddress ma.Multiaddr) (ma.Multiaddr, error)
}
type SenderMatcher interface {
Matches(ctx context.Context, tx []byte, networkID uint64, senderOverlay swarm.Address) ([]byte, error)
}
// Service can perform initiate or handle a handshake between peers.
type Service struct {
signer crypto.Signer
advertisableAddresser AdvertisableAddressResolver
senderMatcher SenderMatcher
overlay swarm.Address
fullNode bool
transaction []byte
networkID uint64
welcomeMessage atomic.Value
receivedHandshakes map[libp2ppeer.ID]struct{}
receivedHandshakesMu sync.Mutex
logger logging.Logger
libp2pID libp2ppeer.ID
network.Notifiee // handshake service can be the receiver for network.Notify
}
// Info contains the information received from the handshake.
type Info struct {
BzzAddress *bzz.Address
FullNode bool
}
func (i *Info) LightString() string {
if !i.FullNode {
return " (light)"
}
return ""
}
// New creates a new handshake Service.
func New(signer crypto.Signer, advertisableAddresser AdvertisableAddressResolver, isSender SenderMatcher, overlay swarm.Address, networkID uint64, fullNode bool, transaction []byte, welcomeMessage string, ownPeerID libp2ppeer.ID, logger logging.Logger) (*Service, error) {
if len(welcomeMessage) > MaxWelcomeMessageLength {
return nil, ErrWelcomeMessageLength
}
svc := &Service{
signer: signer,
advertisableAddresser: advertisableAddresser,
overlay: overlay,
networkID: networkID,
fullNode: fullNode,
transaction: transaction,
senderMatcher: isSender,
receivedHandshakes: make(map[libp2ppeer.ID]struct{}),
libp2pID: ownPeerID,
logger: logger,
Notifiee: new(network.NoopNotifiee),
}
svc.welcomeMessage.Store(welcomeMessage)
return svc, nil
}
// Handshake initiates a handshake with a peer.
func (s *Service) Handshake(ctx context.Context, stream p2p.Stream, peerMultiaddr ma.Multiaddr, peerID libp2ppeer.ID) (i *Info, err error) {
ctx, cancel := context.WithTimeout(ctx, handshakeTimeout)
defer cancel()
w, r := protobuf.NewWriterAndReader(stream)
fullRemoteMA, err := buildFullMA(peerMultiaddr, peerID)
if err != nil {
return nil, err
}
fullRemoteMABytes, err := fullRemoteMA.MarshalBinary()
if err != nil {
return nil, err
}
if err := w.WriteMsgWithContext(ctx, &pb.Syn{
ObservedUnderlay: fullRemoteMABytes,
}); err != nil {
return nil, fmt.Errorf("write syn message: %w", err)
}
var resp pb.SynAck
if err := r.ReadMsgWithContext(ctx, &resp); err != nil {
return nil, fmt.Errorf("read synack message: %w", err)
}
observedUnderlay, err := ma.NewMultiaddrBytes(resp.Syn.ObservedUnderlay)
if err != nil {
return nil, ErrInvalidSyn
}
observedUnderlayAddrInfo, err := libp2ppeer.AddrInfoFromP2pAddr(observedUnderlay)
if err != nil {
return nil, fmt.Errorf("extract addr from P2P: %w", err)
}
if s.libp2pID != observedUnderlayAddrInfo.ID {
//NOTE eventually we will return error here, but for now we want to gather some statistics
s.logger.Warningf("received peer ID %s does not match ours: %s", observedUnderlayAddrInfo.ID, s.libp2pID)
}
advertisableUnderlay, err := s.advertisableAddresser.Resolve(observedUnderlay)
if err != nil {
return nil, err
}
bzzAddress, err := bzz.NewAddress(s.signer, advertisableUnderlay, s.overlay, s.networkID, s.transaction)
if err != nil {
return nil, err
}
advertisableUnderlayBytes, err := bzzAddress.Underlay.MarshalBinary()
if err != nil {
return nil, err
}
overlay := swarm.NewAddress(resp.Ack.Address.Overlay)
if resp.Ack.NetworkID != s.networkID {
return nil, ErrNetworkIDIncompatible
}
blockHash, err := s.senderMatcher.Matches(ctx, resp.Ack.Transaction, s.networkID, overlay)
if err != nil {
return nil, fmt.Errorf("overlay %v verification failed: %w", overlay, err)
}
remoteBzzAddress, err := s.parseCheckAck(resp.Ack, blockHash)
if err != nil {
return nil, err
}
// Synced read:
welcomeMessage := s.GetWelcomeMessage()
if err := w.WriteMsgWithContext(ctx, &pb.Ack{
Address: &pb.BzzAddress{
Underlay: advertisableUnderlayBytes,
Overlay: bzzAddress.Overlay.Bytes(),
Signature: bzzAddress.Signature,
},
NetworkID: s.networkID,
FullNode: s.fullNode,
Transaction: s.transaction,
WelcomeMessage: welcomeMessage,
}); err != nil {
return nil, fmt.Errorf("write ack message: %w", err)
}
s.logger.Tracef("handshake finished for peer (outbound) %s", remoteBzzAddress.Overlay.String())
if len(resp.Ack.WelcomeMessage) > 0 {
s.logger.Infof("greeting \"%s\" from peer: %s", resp.Ack.WelcomeMessage, remoteBzzAddress.Overlay.String())
}
return &Info{
BzzAddress: remoteBzzAddress,
FullNode: resp.Ack.FullNode,
}, nil
}
// Handle handles an incoming handshake from a peer.
func (s *Service) Handle(ctx context.Context, stream p2p.Stream, remoteMultiaddr ma.Multiaddr, remotePeerID libp2ppeer.ID) (i *Info, err error) {
ctx, cancel := context.WithTimeout(ctx, handshakeTimeout)
defer cancel()
s.receivedHandshakesMu.Lock()
if _, exists := s.receivedHandshakes[remotePeerID]; exists {
s.receivedHandshakesMu.Unlock()
return nil, ErrHandshakeDuplicate
}
s.receivedHandshakes[remotePeerID] = struct{}{}
s.receivedHandshakesMu.Unlock()
w, r := protobuf.NewWriterAndReader(stream)
fullRemoteMA, err := buildFullMA(remoteMultiaddr, remotePeerID)
if err != nil {
return nil, err
}
fullRemoteMABytes, err := fullRemoteMA.MarshalBinary()
if err != nil {
return nil, err
}
var syn pb.Syn
if err := r.ReadMsgWithContext(ctx, &syn); err != nil {
return nil, fmt.Errorf("read syn message: %w", err)
}
observedUnderlay, err := ma.NewMultiaddrBytes(syn.ObservedUnderlay)
if err != nil {
return nil, ErrInvalidSyn
}
advertisableUnderlay, err := s.advertisableAddresser.Resolve(observedUnderlay)
if err != nil {
return nil, err
}
bzzAddress, err := bzz.NewAddress(s.signer, advertisableUnderlay, s.overlay, s.networkID, s.transaction)
if err != nil {
return nil, err
}
advertisableUnderlayBytes, err := bzzAddress.Underlay.MarshalBinary()
if err != nil {
return nil, err
}
welcomeMessage := s.GetWelcomeMessage()
if err := w.WriteMsgWithContext(ctx, &pb.SynAck{
Syn: &pb.Syn{
ObservedUnderlay: fullRemoteMABytes,
},
Ack: &pb.Ack{
Address: &pb.BzzAddress{
Underlay: advertisableUnderlayBytes,
Overlay: bzzAddress.Overlay.Bytes(),
Signature: bzzAddress.Signature,
},
NetworkID: s.networkID,
FullNode: s.fullNode,
Transaction: s.transaction,
WelcomeMessage: welcomeMessage,
},
}); err != nil {
return nil, fmt.Errorf("write synack message: %w", err)
}
var ack pb.Ack
if err := r.ReadMsgWithContext(ctx, &ack); err != nil {
return nil, fmt.Errorf("read ack message: %w", err)
}
if ack.NetworkID != s.networkID {
return nil, ErrNetworkIDIncompatible
}
overlay := swarm.NewAddress(ack.Address.Overlay)
blockHash, err := s.senderMatcher.Matches(ctx, ack.Transaction, s.networkID, overlay)
if err != nil {
return nil, fmt.Errorf("overlay %v verification failed: %w", overlay, err)
}
remoteBzzAddress, err := s.parseCheckAck(&ack, blockHash)
if err != nil {
return nil, err
}
s.logger.Tracef("handshake finished for peer (inbound) %s", remoteBzzAddress.Overlay.String())
if len(ack.WelcomeMessage) > 0 {
s.logger.Infof("greeting \"%s\" from peer: %s", ack.WelcomeMessage, remoteBzzAddress.Overlay.String())
}
return &Info{
BzzAddress: remoteBzzAddress,
FullNode: ack.FullNode,
}, nil
}
// Disconnected is called when the peer disconnects.
func (s *Service) Disconnected(_ network.Network, c network.Conn) {
s.receivedHandshakesMu.Lock()
defer s.receivedHandshakesMu.Unlock()
delete(s.receivedHandshakes, c.RemotePeer())
}
// SetWelcomeMessage sets the new handshake welcome message.
func (s *Service) SetWelcomeMessage(msg string) (err error) {
if len(msg) > MaxWelcomeMessageLength {
return ErrWelcomeMessageLength
}
s.welcomeMessage.Store(msg)
return nil
}
// GetWelcomeMessage returns the the current handshake welcome message.
func (s *Service) GetWelcomeMessage() string {
return s.welcomeMessage.Load().(string)
}
func buildFullMA(addr ma.Multiaddr, peerID libp2ppeer.ID) (ma.Multiaddr, error) {
return ma.NewMultiaddr(fmt.Sprintf("%s/p2p/%s", addr.String(), peerID.Pretty()))
}
func (s *Service) parseCheckAck(ack *pb.Ack, blockHash []byte) (*bzz.Address, error) {
bzzAddress, err := bzz.ParseAddress(ack.Address.Underlay, ack.Address.Overlay, ack.Address.Signature, ack.Transaction, blockHash, s.networkID)
if err != nil {
return nil, ErrInvalidAck
}
return bzzAddress, nil
}