Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions p2p/enode/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package enode
import (
"crypto/ecdsa"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
Expand Down Expand Up @@ -358,9 +359,10 @@ func ParseID(in string) (ID, error) {
// Returns -1 if a is closer to target, 1 if b is closer to target
// and 0 if they are equal.
func DistCmp(target, a, b ID) int {
for i := range target {
da := a[i] ^ target[i]
db := b[i] ^ target[i]
for i := 0; i < len(target); i += 8 {
tn := binary.BigEndian.Uint64(target[i : i+8])
da := tn ^ binary.BigEndian.Uint64(a[i:i+8])
db := tn ^ binary.BigEndian.Uint64(b[i:i+8])
if da > db {
return 1
} else if da < db {
Expand Down
10 changes: 10 additions & 0 deletions p2p/enode/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,16 @@ func TestID_distcmpEqual(t *testing.T) {
}
}

func BenchmarkDistCmp(b *testing.B) {
base := ID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
aID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
bID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = DistCmp(base, aID, bID)
}
}

func TestID_logdist(t *testing.T) {
logdistBig := func(a, b ID) int {
abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:])
Expand Down