From 0caafd8e875a637985518375683e17a6710066d5 Mon Sep 17 00:00:00 2001
From: Matt Joiner <anacrolix@gmail.com>
Date: Sat, 16 Jun 2018 16:40:37 +1000
Subject: [PATCH] Allow dropping connections to the same peer ID

Necessary for a test that expects one connection to each other Client.
---
 config.go  |  1 +
 torrent.go | 14 ++++++++++++++
 2 files changed, 15 insertions(+)

diff --git a/config.go b/config.go
index f438cbce..899a2f06 100644
--- a/config.go
+++ b/config.go
@@ -110,6 +110,7 @@ type ClientConfig struct {
 	PublicIp6 net.IP
 
 	DisableAcceptRateLimiting bool
+	dropDuplicatePeerIds      bool
 }
 
 func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig {
diff --git a/torrent.go b/torrent.go
index 62c61a10..3259dcc4 100644
--- a/torrent.go
+++ b/torrent.go
@@ -1503,6 +1503,20 @@ func (t *Torrent) addConnection(c *connection) (err error) {
 	if t.closed.IsSet() {
 		return errors.New("torrent closed")
 	}
+	for c0 := range t.conns {
+		if c.PeerID != c0.PeerID {
+			continue
+		}
+		if !t.cl.config.dropDuplicatePeerIds {
+			continue
+		}
+		if left, ok := c.hasPreferredNetworkOver(c0); ok && left {
+			c0.Close()
+			t.deleteConnection(c0)
+		} else {
+			return errors.New("existing connection preferred")
+		}
+	}
 	if !t.wantConns() {
 		return errors.New("don't want conns")
 	}
-- 
2.51.0