From: Matt Joiner <anacrolix@gmail.com>
Date: Mon, 9 Jul 2018 23:50:39 +0000 (+1000)
Subject: Add more worseConn comparisons
X-Git-Tag: v1.0.0~98
X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=ba9935d522c7aa51ab73d1df49274cf7a14ba6f1;p=btrtrc.git

Add more worseConn comparisons

Should fix #264.
---

diff --git a/connection.go b/connection.go
index 41eb47bd..8239f845 100644
--- a/connection.go
+++ b/connection.go
@@ -1553,3 +1553,15 @@ func (c *connection) setTorrent(t *Torrent) {
 	c.t = t
 	t.reconcileHandshakeStats(c)
 }
+
+func (c *connection) peerPriority() peerPriority {
+	return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
+}
+
+func (c *connection) remoteIp() net.IP {
+	return missinggo.AddrIP(c.remoteAddr())
+}
+
+func (c *connection) remoteIpPort() ipPort {
+	return ipPort{missinggo.AddrIP(c.remoteAddr()), uint16(missinggo.AddrPort(c.remoteAddr()))}
+}
diff --git a/worst_conns.go b/worst_conns.go
index 51a23f12..ad87d1b3 100644
--- a/worst_conns.go
+++ b/worst_conns.go
@@ -1,6 +1,10 @@
 package torrent
 
-import "container/heap"
+import (
+	"container/heap"
+	"fmt"
+	"unsafe"
+)
 
 func worseConn(l, r *connection) bool {
 	var ml multiLess
@@ -11,7 +15,13 @@ func worseConn(l, r *connection) bool {
 	ml.StrictNext(
 		l.completedHandshake.Equal(r.completedHandshake),
 		l.completedHandshake.Before(r.completedHandshake))
-	return ml.Final()
+	ml.StrictNext(l.peerPriority() == r.peerPriority(), l.peerPriority() < r.peerPriority())
+	ml.StrictNext(l == r, uintptr(unsafe.Pointer(l)) < uintptr(unsafe.Pointer(r)))
+	less, ok := ml.FinalOk()
+	if !ok {
+		panic(fmt.Sprintf("cannot differentiate %#v and %#v", l, r))
+	}
+	return less
 }
 
 type worseConnSlice struct {