Skip to content

Commit e34d134

Browse files
committed
p2p: fixes for actual connections
The unit test hooks were turned on 'in production'.
1 parent 8564eb9 commit e34d134

6 files changed

Lines changed: 38 additions & 29 deletions

File tree

‎p2p/message.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,10 @@ func (rw *frameRW) ReadMsg() (msg Msg, err error) {
174174
// read magic and payload size
175175
start := make([]byte, 8)
176176
if _, err = io.ReadFull(rw.bufconn, start); err != nil {
177-
return msg, newPeerError(errRead, "%v", err)
177+
return msg, err
178178
}
179179
if !bytes.HasPrefix(start, magicToken) {
180-
return msg, newPeerError(errMagicTokenMismatch, "got %x, want %x", start[:4], magicToken)
180+
return msg, fmt.Errorf("bad magic token %x", start[:4], magicToken)
181181
}
182182
size := binary.BigEndian.Uint32(start[4:])
183183

‎p2p/peer.go‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package p2p
22

33
import (
4+
"errors"
45
"fmt"
56
"io"
67
"io/ioutil"
@@ -71,7 +72,8 @@ type Peer struct {
7172
runlock sync.RWMutex // protects running
7273
running map[string]*proto
7374

74-
protocolHandshakeEnabled bool
75+
// disables protocol handshake, for testing
76+
noHandshake bool
7577

7678
protoWG sync.WaitGroup
7779
protoErr chan error
@@ -134,11 +136,11 @@ func (p *Peer) Disconnect(reason DiscReason) {
134136

135137
// String implements fmt.Stringer.
136138
func (p *Peer) String() string {
137-
return fmt.Sprintf("Peer %.8x %v", p.remoteID, p.RemoteAddr())
139+
return fmt.Sprintf("Peer %.8x %v", p.remoteID[:], p.RemoteAddr())
138140
}
139141

140142
func newPeer(conn net.Conn, protocols []Protocol, ourName string, ourID, remoteID *discover.NodeID) *Peer {
141-
logtag := fmt.Sprintf("Peer %.8x %v", remoteID, conn.RemoteAddr())
143+
logtag := fmt.Sprintf("Peer %.8x %v", remoteID[:], conn.RemoteAddr())
142144
return &Peer{
143145
Logger: logger.NewLogger(logtag),
144146
rw: newFrameRW(conn, msgWriteTimeout),
@@ -164,54 +166,57 @@ func (p *Peer) run() DiscReason {
164166
var readErr = make(chan error, 1)
165167
defer p.closeProtocols()
166168
defer close(p.closed)
167-
defer p.rw.Close()
168169

169-
// start the read loop
170170
go func() { readErr <- p.readLoop() }()
171171

172-
if p.protocolHandshakeEnabled {
172+
if !p.noHandshake {
173173
if err := writeProtocolHandshake(p.rw, p.ourName, *p.ourID, p.protocols); err != nil {
174174
p.DebugDetailf("Protocol handshake error: %v\n", err)
175+
p.rw.Close()
175176
return DiscProtocolError
176177
}
177178
}
178179

179-
// wait for an error or disconnect
180+
// Wait for an error or disconnect.
180181
var reason DiscReason
181182
select {
182183
case err := <-readErr:
183184
// We rely on protocols to abort if there is a write error. It
184185
// might be more robust to handle them here as well.
185186
p.DebugDetailf("Read error: %v\n", err)
186-
reason = DiscNetworkError
187+
p.rw.Close()
188+
return DiscNetworkError
189+
187190
case err := <-p.protoErr:
188191
reason = discReasonForError(err)
189192
case reason = <-p.disc:
190193
}
191-
if reason != DiscNetworkError {
192-
p.politeDisconnect(reason)
193-
}
194+
p.politeDisconnect(reason)
195+
196+
// Wait for readLoop. It will end because conn is now closed.
197+
<-readErr
194198
p.Debugf("Disconnected: %v\n", reason)
195199
return reason
196200
}
197201

198202
func (p *Peer) politeDisconnect(reason DiscReason) {
199203
done := make(chan struct{})
200204
go func() {
201-
// send reason
202205
EncodeMsg(p.rw, discMsg, uint(reason))
203-
// discard any data that might arrive
206+
// Wait for the other side to close the connection.
207+
// Discard any data that they send until then.
204208
io.Copy(ioutil.Discard, p.rw)
205209
close(done)
206210
}()
207211
select {
208212
case <-done:
209213
case <-time.After(disconnectGracePeriod):
210214
}
215+
p.rw.Close()
211216
}
212217

213218
func (p *Peer) readLoop() error {
214-
if p.protocolHandshakeEnabled {
219+
if !p.noHandshake {
215220
if err := readProtocolHandshake(p, p.rw); err != nil {
216221
return err
217222
}
@@ -264,7 +269,7 @@ func readProtocolHandshake(p *Peer, rw MsgReadWriter) error {
264269
return newPeerError(errProtocolBreach, "expected handshake, got %x", msg.Code)
265270
}
266271
if msg.Size > baseProtocolMaxMsgSize {
267-
return newPeerError(errMisc, "message too big")
272+
return newPeerError(errInvalidMsg, "message too big")
268273
}
269274
var hs handshake
270275
if err := msg.Decode(&hs); err != nil {
@@ -326,7 +331,7 @@ func (p *Peer) startProto(offset uint64, impl Protocol) *proto {
326331
err := impl.Run(p, rw)
327332
if err == nil {
328333
p.DebugDetailf("Protocol %s/%d returned\n", impl.Name, impl.Version)
329-
err = newPeerError(errMisc, "protocol returned")
334+
err = errors.New("protocol returned")
330335
} else {
331336
p.DebugDetailf("Protocol %s/%d error: %v\n", impl.Name, impl.Version, err)
332337
}

‎p2p/peer_error.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func discReasonForError(err error) DiscReason {
123123
return DiscProtocolError
124124
case errPingTimeout:
125125
return DiscReadTimeout
126-
case errRead, errWrite, errMisc:
126+
case errRead, errWrite:
127127
return DiscNetworkError
128128
default:
129129
return DiscSubprotocolError

‎p2p/peer_test.go‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ var discard = Protocol{
3030
},
3131
}
3232

33-
func testPeer(handshake bool, protos []Protocol) (*frameRW, *Peer, <-chan DiscReason) {
33+
func testPeer(noHandshake bool, protos []Protocol) (*frameRW, *Peer, <-chan DiscReason) {
3434
conn1, conn2 := net.Pipe()
3535
peer := newPeer(conn1, protos, "name", &discover.NodeID{}, &discover.NodeID{})
36-
peer.protocolHandshakeEnabled = handshake
36+
peer.noHandshake = noHandshake
3737
errc := make(chan DiscReason, 1)
3838
go func() { errc <- peer.run() }()
3939
return newFrameRW(conn2, msgWriteTimeout), peer, errc
@@ -61,7 +61,7 @@ func TestPeerProtoReadMsg(t *testing.T) {
6161
},
6262
}
6363

64-
rw, peer, errc := testPeer(false, []Protocol{proto})
64+
rw, peer, errc := testPeer(true, []Protocol{proto})
6565
defer rw.Close()
6666
peer.startSubprotocols([]Cap{proto.cap()})
6767

@@ -100,7 +100,7 @@ func TestPeerProtoReadLargeMsg(t *testing.T) {
100100
},
101101
}
102102

103-
rw, peer, errc := testPeer(false, []Protocol{proto})
103+
rw, peer, errc := testPeer(true, []Protocol{proto})
104104
defer rw.Close()
105105
peer.startSubprotocols([]Cap{proto.cap()})
106106

@@ -130,7 +130,7 @@ func TestPeerProtoEncodeMsg(t *testing.T) {
130130
return nil
131131
},
132132
}
133-
rw, peer, _ := testPeer(false, []Protocol{proto})
133+
rw, peer, _ := testPeer(true, []Protocol{proto})
134134
defer rw.Close()
135135
peer.startSubprotocols([]Cap{proto.cap()})
136136

@@ -142,7 +142,7 @@ func TestPeerProtoEncodeMsg(t *testing.T) {
142142
func TestPeerWriteForBroadcast(t *testing.T) {
143143
defer testlog(t).detach()
144144

145-
rw, peer, peerErr := testPeer(false, []Protocol{discard})
145+
rw, peer, peerErr := testPeer(true, []Protocol{discard})
146146
defer rw.Close()
147147
peer.startSubprotocols([]Cap{discard.cap()})
148148

@@ -179,7 +179,7 @@ func TestPeerWriteForBroadcast(t *testing.T) {
179179
func TestPeerPing(t *testing.T) {
180180
defer testlog(t).detach()
181181

182-
rw, _, _ := testPeer(false, nil)
182+
rw, _, _ := testPeer(true, nil)
183183
defer rw.Close()
184184
if err := EncodeMsg(rw, pingMsg); err != nil {
185185
t.Fatal(err)
@@ -192,7 +192,7 @@ func TestPeerPing(t *testing.T) {
192192
func TestPeerDisconnect(t *testing.T) {
193193
defer testlog(t).detach()
194194

195-
rw, _, disc := testPeer(false, nil)
195+
rw, _, disc := testPeer(true, nil)
196196
defer rw.Close()
197197
if err := EncodeMsg(rw, discMsg, DiscQuitting); err != nil {
198198
t.Fatal(err)
@@ -233,7 +233,7 @@ func TestPeerHandshake(t *testing.T) {
233233
{Name: "c", Version: 3, Length: 1, Run: run},
234234
{Name: "d", Version: 4, Length: 1, Run: run},
235235
}
236-
rw, p, disc := testPeer(true, protocols)
236+
rw, p, disc := testPeer(false, protocols)
237237
p.remoteID = remote.ourID
238238
defer rw.Close()
239239

@@ -269,6 +269,7 @@ func TestPeerHandshake(t *testing.T) {
269269
}
270270

271271
close(stop)
272+
expectMsg(rw, discMsg, nil)
272273
t.Logf("disc reason: %v", <-disc)
273274
}
274275

‎p2p/server.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,9 @@ func (srv *Server) startPeer(conn net.Conn, dest *discover.Node) {
408408
return
409409
}
410410

411-
srv.newPeerHook(p)
411+
if srv.newPeerHook != nil {
412+
srv.newPeerHook(p)
413+
}
412414
p.run()
413415
srv.removePeer(p)
414416
}

‎p2p/server_test.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ func TestServerBroadcast(t *testing.T) {
118118
srv := startTestServer(t, func(p *Peer) {
119119
p.protocols = []Protocol{discard}
120120
p.startSubprotocols([]Cap{discard.cap()})
121+
p.noHandshake = true
121122
connected.Done()
122123
})
123124
defer srv.Stop()

0 commit comments

Comments
 (0)