@@ -347,7 +347,8 @@ func (ids *idService) sendPushes(ctx context.Context) {
347
347
defer func () { <- sem }()
348
348
ctx , cancel := context .WithTimeout (ctx , 5 * time .Second )
349
349
defer cancel ()
350
- str , err := ids .Host .NewStream (ctx , c .RemotePeer (), IDPush )
350
+
351
+ str , err := newStreamAndNegotiate (ctx , c , IDPush )
351
352
if err != nil { // connection might have been closed recently
352
353
return
353
354
}
@@ -437,25 +438,38 @@ func (ids *idService) IdentifyWait(c network.Conn) <-chan struct{} {
437
438
return e .IdentifyWaitChan
438
439
}
439
440
440
- func (ids * idService ) identifyConn (c network.Conn ) error {
441
- ctx , cancel := context .WithTimeout (context .Background (), Timeout )
442
- defer cancel ()
441
+ // newStreamAndNegotiate opens a new stream on the given connection and negotiates the given protocol.
442
+ func newStreamAndNegotiate (ctx context.Context , c network.Conn , proto protocol.ID ) (network.Stream , error ) {
443
443
s , err := c .NewStream (network .WithAllowLimitedConn (ctx , "identify" ))
444
444
if err != nil {
445
445
log .Debugw ("error opening identify stream" , "peer" , c .RemotePeer (), "error" , err )
446
- return err
446
+ return nil , err
447
+ }
448
+ err = s .SetDeadline (time .Now ().Add (Timeout ))
449
+ if err != nil {
450
+ return nil , err
447
451
}
448
- s .SetDeadline (time .Now ().Add (Timeout ))
449
452
450
- if err := s .SetProtocol (ID ); err != nil {
453
+ if err := s .SetProtocol (proto ); err != nil {
451
454
log .Warnf ("error setting identify protocol for stream: %s" , err )
452
- s .Reset ()
455
+ _ = s .Reset ()
453
456
}
454
457
455
458
// ok give the response to our handler.
456
- if err := msmux .SelectProtoOrFail (ID , s ); err != nil {
459
+ if err := msmux .SelectProtoOrFail (proto , s ); err != nil {
457
460
log .Infow ("failed negotiate identify protocol with peer" , "peer" , c .RemotePeer (), "error" , err )
458
- s .Reset ()
461
+ _ = s .Reset ()
462
+ return nil , err
463
+ }
464
+ return s , nil
465
+ }
466
+
467
+ func (ids * idService ) identifyConn (c network.Conn ) error {
468
+ ctx , cancel := context .WithTimeout (context .Background (), Timeout )
469
+ defer cancel ()
470
+ s , err := newStreamAndNegotiate (network .WithAllowLimitedConn (ctx , "identify" ), c , ID )
471
+ if err != nil {
472
+ log .Debugw ("error opening identify stream" , "peer" , c .RemotePeer (), "error" , err )
459
473
return err
460
474
}
461
475
0 commit comments