diff --git a/p2p/peer.go b/p2p/peer.go index 35556a59..ecf2efce 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -92,6 +92,7 @@ func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs [] } return nil, err } + return peer, nil } @@ -218,13 +219,12 @@ func (p *peer) Addr() net.Addr { // PubKey returns peer's public key. func (p *peer) PubKey() crypto.PubKey { - if p.config.AuthEnc { + if p.NodeInfo() != nil { + return p.nodeInfo.PubKey + } else if p.config.AuthEnc { return p.conn.(*SecretConnection).RemotePubKey() } - if p.NodeInfo() == nil { - panic("Attempt to get peer's PubKey before calling Handshake") - } - return p.PubKey() + panic("Attempt to get peer's PubKey before calling Handshake") } // OnStart implements BaseService. @@ -306,7 +306,7 @@ func (p *peer) Set(key string, data interface{}) { // Key returns the peer's ID - the hex encoded hash of its pubkey. func (p *peer) ID() ID { - return ID(hex.EncodeToString(p.nodeInfo.PubKey.Address())) + return ID(hex.EncodeToString(p.PubKey().Address())) } // NodeInfo returns a copy of the peer's NodeInfo. diff --git a/p2p/switch.go b/p2p/switch.go index 22d3d5a5..e86acfad 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -239,9 +239,8 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // NOTE: If error is returned, caller is responsible for calling peer.CloseConn() func (sw *Switch) addPeer(peer *peer) error { - // Avoid self - if sw.nodeInfo.PubKey.Equals(peer.PubKey().Wrap()) { + if sw.nodeKey.ID() == peer.ID() { return errors.New("Ignoring connection from self") } @@ -385,6 +384,14 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (Peer, return nil, err } peer.SetLogger(sw.Logger.With("peer", addr)) + + // authenticate peer + if addr.ID == "" { + peer.Logger.Info("Dialed peer with unknown ID - unable to authenticate", "addr", addr) + } else if addr.ID != peer.ID() { + return nil, fmt.Errorf("Failed to authenticate peer %v. Connected to peer with ID %s", addr, peer.ID()) + } + if persistent { peer.makePersistent() }