From 225d0095b3c19376fe3999f0ffa528225c1c8c76 Mon Sep 17 00:00:00 2001 From: cuiweixie Date: Sun, 12 Oct 2025 20:00:44 +0800 Subject: [PATCH 1/2] p2p/enode: opt LogDist --- p2p/enode/node.go | 15 ++++++++++----- p2p/enode/node_test.go | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/p2p/enode/node.go b/p2p/enode/node.go index d6f2ac7ff562..5ea8d288ecc3 100644 --- a/p2p/enode/node.go +++ b/p2p/enode/node.go @@ -19,6 +19,7 @@ package enode import ( "crypto/ecdsa" "encoding/base64" + "encoding/binary" "encoding/hex" "errors" "fmt" @@ -372,15 +373,19 @@ func DistCmp(target, a, b ID) int { // LogDist returns the logarithmic distance between a and b, log2(a ^ b). func LogDist(a, b ID) int { + lenA := len(a) + totalBits := lenA * 8 lz := 0 - for i := range a { - x := a[i] ^ b[i] + for i := 0; i < lenA; i += 8 { + ai := binary.BigEndian.Uint64(a[i : i+8]) + bi := binary.BigEndian.Uint64(b[i : i+8]) + x := ai ^ bi if x == 0 { - lz += 8 + lz += 64 } else { - lz += bits.LeadingZeros8(x) + lz += bits.LeadingZeros64(x) break } } - return len(a)*8 - lz + return totalBits - lz } diff --git a/p2p/enode/node_test.go b/p2p/enode/node_test.go index e9fe631f3459..f276af663883 100644 --- a/p2p/enode/node_test.go +++ b/p2p/enode/node_test.go @@ -378,6 +378,28 @@ func TestID_logdist(t *testing.T) { } } +func makeIDs() (ID, ID) { + var a, b ID + size := len(a) + // last byte differs + for i := 0; i < size-1; i++ { + a[i] = 0xAA + b[i] = 0xAA + } + a[size-1] = 0xAA + b[size-1] = 0xAB + return a, b +} + +// Benchmark LogDist +func BenchmarkLogDist(b *testing.B) { + aID, bID := makeIDs() // 256-bit ID + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = LogDist(aID, bID) + } +} + // The random tests is likely to miss the case where a and b are equal, // this test checks it explicitly. func TestID_logdistEqual(t *testing.T) { From 250ad041e5eacc5d1c9709fff2e596ae67ebb87b Mon Sep 17 00:00:00 2001 From: Felix Lange Date: Mon, 13 Oct 2025 13:09:12 +0200 Subject: [PATCH 2/2] Revert variable addition --- p2p/enode/node.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/p2p/enode/node.go b/p2p/enode/node.go index 5ea8d288ecc3..8198050353bd 100644 --- a/p2p/enode/node.go +++ b/p2p/enode/node.go @@ -373,10 +373,8 @@ func DistCmp(target, a, b ID) int { // LogDist returns the logarithmic distance between a and b, log2(a ^ b). func LogDist(a, b ID) int { - lenA := len(a) - totalBits := lenA * 8 lz := 0 - for i := 0; i < lenA; i += 8 { + for i := 0; i < len(a); i += 8 { ai := binary.BigEndian.Uint64(a[i : i+8]) bi := binary.BigEndian.Uint64(b[i : i+8]) x := ai ^ bi @@ -387,5 +385,5 @@ func LogDist(a, b ID) int { break } } - return totalBits - lz + return len(a)*8 - lz }