From: Matt Joiner Date: Tue, 9 Dec 2014 06:25:49 +0000 (-0600) Subject: dht: We can now message nodes with no ID if there's nothing better X-Git-Tag: v1.0.0~1393 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=b52f866e907c16e5f7401514819444b48d984424;p=btrtrc.git dht: We can now message nodes with no ID if there's nothing better --- diff --git a/dht/dht.go b/dht/dht.go index d688f770..d1abce94 100644 --- a/dht/dht.go +++ b/dht/dht.go @@ -1104,8 +1104,33 @@ func (me bitCountDistance) IsZero() bool { } // Below are 2 versions of idDistance. Only one can be active. +var maxDistance big.Int +func init() { + var zero big.Int + maxDistance.SetBit(&zero, 160, 1) +} + +// If we don't know the ID for a node, then its distance is more than the +// furthest possible distance otherwise. func idDistance(a, b string) (ret bigIntDistance) { + if a == "" && b == "" { + return + } + if a == "" { + if len(b) != 20 { + panic(b) + } + ret.Set(&maxDistance) + return + } + if b == "" { + if len(a) != 20 { + panic(a) + } + ret.Set(&maxDistance) + return + } if len(a) != 20 { panic(a) } diff --git a/dht/dht_test.go b/dht/dht_test.go index 5b5b5d1d..137aa136 100644 --- a/dht/dht_test.go +++ b/dht/dht_test.go @@ -52,6 +52,7 @@ var testIDs = []string{ "\x03" + zeroID[1:18] + "\x55\xf0", "\x55" + zeroID[1:17] + "\xff\x55\x0f", "\x54" + zeroID[1:18] + "\x50\x0f", + "", } func TestDistances(t *testing.T) { @@ -64,21 +65,38 @@ func TestDistances(t *testing.T) { if idDistance(testIDs[3], testIDs[2]).BitCount() != 4+8+8 { t.FailNow() } + for i := 0; i < 5; i++ { + dist := idDistance(testIDs[i], testIDs[5]).Int + if dist.Cmp(&maxDistance) != 0 { + t.FailNow() + } + } +} + +func TestMaxDistanceString(t *testing.T) { + if string(maxDistance.Bytes()) != "\x01"+zeroID { + t.FailNow() + } } func TestBadIdStrings(t *testing.T) { var a, b string + idDistance(a, b) + idDistance(a, zeroID) + idDistance(zeroID, b) recoverPanicOrDie(t, func() { - idDistance(a, b) + idDistance("when", a) }) recoverPanicOrDie(t, func() { - idDistance(a, zeroID) + idDistance(a, "bad") }) recoverPanicOrDie(t, func() { - idDistance(zeroID, b) + idDistance("meets", "evil") }) - if !idDistance(zeroID, zeroID).IsZero() { - t.Fatal("identical IDs should have distance 0") + for _, id := range testIDs { + if !idDistance(id, id).IsZero() { + t.Fatal("identical IDs should have distance 0") + } } a = "\x03" + zeroID[1:] b = zeroID