dht/dht.go | 25 +++++++++++++++++++++++++ dht/dht_test.go | 28 +++++++++++++++++++++++----- diff --git a/dht/dht.go b/dht/dht.go index d688f770b9af79d25bd4ad91204fd20ba1a1c149..d1abce948e239d182a44933d1e674e86889f64bc 100644 --- a/dht/dht.go +++ b/dht/dht.go @@ -1104,8 +1104,33 @@ return me == 0 } // 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 5b5b5d1d5fdbe055a9069c97feafc9ec5b6c60ba..137aa1366ee2f6e37ef0a4bba7afd119be323f86 100644 --- a/dht/dht_test.go +++ b/dht/dht_test.go @@ -52,6 +52,7 @@ "\x03" + zeroID[1:], "\x03" + zeroID[1:18] + "\x55\xf0", "\x55" + zeroID[1:17] + "\xff\x55\x0f", "\x54" + zeroID[1:18] + "\x50\x0f", + "", } func TestDistances(t *testing.T) { @@ -63,22 +64,39 @@ t.FailNow() } 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