p2p/discover: remove type encPubkey (#30172)

The pubkey type was moved to package v4wire a long time ago. Remaining uses of
encPubkey were probably left in due to laziness.
This commit is contained in:
Felix Lange 2024-07-18 11:09:02 +02:00 committed by GitHub
parent f59d013e40
commit ad49c708f5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 23 additions and 54 deletions

@ -17,16 +17,10 @@
package discover package discover
import ( import (
"crypto/ecdsa"
"crypto/elliptic"
"errors"
"math/big"
"slices" "slices"
"sort" "sort"
"time" "time"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
) )
@ -48,33 +42,6 @@ type tableNode struct {
isValidatedLive bool // true if existence of node is considered validated right now isValidatedLive bool // true if existence of node is considered validated right now
} }
type encPubkey [64]byte
func encodePubkey(key *ecdsa.PublicKey) encPubkey {
var e encPubkey
math.ReadBits(key.X, e[:len(e)/2])
math.ReadBits(key.Y, e[len(e)/2:])
return e
}
func decodePubkey(curve elliptic.Curve, e []byte) (*ecdsa.PublicKey, error) {
if len(e) != len(encPubkey{}) {
return nil, errors.New("wrong size public key data")
}
p := &ecdsa.PublicKey{Curve: curve, X: new(big.Int), Y: new(big.Int)}
half := len(e) / 2
p.X.SetBytes(e[:half])
p.Y.SetBytes(e[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) {
return nil, errors.New("invalid curve point")
}
return p, nil
}
func (e encPubkey) id() enode.ID {
return enode.ID(crypto.Keccak256Hash(e[:]))
}
func unwrapNodes(ns []*tableNode) []*enode.Node { func unwrapNodes(ns []*tableNode) []*enode.Node {
result := make([]*enode.Node, len(ns)) result := make([]*enode.Node, len(ns))
for i, n := range ns { for i, n := range ns {

@ -30,6 +30,7 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/discover/v4wire"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/p2p/enr"
) )
@ -284,7 +285,7 @@ func hexEncPrivkey(h string) *ecdsa.PrivateKey {
} }
// hexEncPubkey decodes h as a public key. // hexEncPubkey decodes h as a public key.
func hexEncPubkey(h string) (ret encPubkey) { func hexEncPubkey(h string) (ret v4wire.Pubkey) {
b, err := hex.DecodeString(h) b, err := hex.DecodeString(h)
if err != nil { if err != nil {
panic(err) panic(err)

@ -34,7 +34,7 @@ func TestUDPv4_Lookup(t *testing.T) {
test := newUDPTest(t) test := newUDPTest(t)
// Lookup on empty table returns no nodes. // Lookup on empty table returns no nodes.
targetKey, _ := decodePubkey(crypto.S256(), lookupTestnet.target[:]) targetKey, _ := v4wire.DecodePubkey(crypto.S256(), lookupTestnet.target)
if results := test.udp.LookupPubkey(targetKey); len(results) > 0 { if results := test.udp.LookupPubkey(targetKey); len(results) > 0 {
t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results) t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results)
} }
@ -56,7 +56,7 @@ func TestUDPv4_Lookup(t *testing.T) {
results := <-resultC results := <-resultC
t.Logf("results:") t.Logf("results:")
for _, e := range results { for _, e := range results {
t.Logf(" ld=%d, %x", enode.LogDist(lookupTestnet.target.id(), e.ID()), e.ID().Bytes()) t.Logf(" ld=%d, %x", enode.LogDist(lookupTestnet.target.ID(), e.ID()), e.ID().Bytes())
} }
if len(results) != bucketSize { if len(results) != bucketSize {
t.Errorf("wrong number of results: got %d, want %d", len(results), bucketSize) t.Errorf("wrong number of results: got %d, want %d", len(results), bucketSize)
@ -142,7 +142,7 @@ func serveTestnet(test *udpTest, testnet *preminedTestnet) {
case *v4wire.Ping: case *v4wire.Ping:
test.packetInFrom(nil, key, to, &v4wire.Pong{Expiration: futureExp, ReplyTok: hash}) test.packetInFrom(nil, key, to, &v4wire.Pong{Expiration: futureExp, ReplyTok: hash})
case *v4wire.Findnode: case *v4wire.Findnode:
dist := enode.LogDist(n.ID(), testnet.target.id()) dist := enode.LogDist(n.ID(), testnet.target.ID())
nodes := testnet.nodesAtDistance(dist - 1) nodes := testnet.nodesAtDistance(dist - 1)
test.packetInFrom(nil, key, to, &v4wire.Neighbors{Expiration: futureExp, Nodes: nodes}) test.packetInFrom(nil, key, to, &v4wire.Neighbors{Expiration: futureExp, Nodes: nodes})
} }
@ -156,12 +156,12 @@ func checkLookupResults(t *testing.T, tn *preminedTestnet, results []*enode.Node
t.Helper() t.Helper()
t.Logf("results:") t.Logf("results:")
for _, e := range results { for _, e := range results {
t.Logf(" ld=%d, %x", enode.LogDist(tn.target.id(), e.ID()), e.ID().Bytes()) t.Logf(" ld=%d, %x", enode.LogDist(tn.target.ID(), e.ID()), e.ID().Bytes())
} }
if hasDuplicates(results) { if hasDuplicates(results) {
t.Errorf("result set contains duplicate entries") t.Errorf("result set contains duplicate entries")
} }
if !sortedByDistanceTo(tn.target.id(), results) { if !sortedByDistanceTo(tn.target.ID(), results) {
t.Errorf("result set not sorted by distance to target") t.Errorf("result set not sorted by distance to target")
} }
wantNodes := tn.closest(len(results)) wantNodes := tn.closest(len(results))
@ -231,7 +231,7 @@ var lookupTestnet = &preminedTestnet{
} }
type preminedTestnet struct { type preminedTestnet struct {
target encPubkey target v4wire.Pubkey
dists [hashBits + 1][]*ecdsa.PrivateKey dists [hashBits + 1][]*ecdsa.PrivateKey
} }
@ -304,7 +304,7 @@ func (tn *preminedTestnet) closest(n int) (nodes []*enode.Node) {
} }
} }
slices.SortFunc(nodes, func(a, b *enode.Node) int { slices.SortFunc(nodes, func(a, b *enode.Node) int {
return enode.DistCmp(tn.target.id(), a.ID(), b.ID()) return enode.DistCmp(tn.target.ID(), a.ID(), b.ID())
}) })
return nodes[:n] return nodes[:n]
} }
@ -319,11 +319,11 @@ func (tn *preminedTestnet) mine() {
tn.dists[i] = nil tn.dists[i] = nil
} }
targetSha := tn.target.id() targetSha := tn.target.ID()
found, need := 0, 40 found, need := 0, 40
for found < need { for found < need {
k := newkey() k := newkey()
ld := enode.LogDist(targetSha, encodePubkey(&k.PublicKey).id()) ld := enode.LogDist(targetSha, v4wire.EncodePubkey(&k.PublicKey).ID())
if len(tn.dists[ld]) < 8 { if len(tn.dists[ld]) < 8 {
tn.dists[ld] = append(tn.dists[ld], k) tn.dists[ld] = append(tn.dists[ld], k)
found++ found++

@ -271,7 +271,7 @@ func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
// case and run the bootstrapping logic. // case and run the bootstrapping logic.
<-t.tab.refresh() <-t.tab.refresh()
} }
return t.newLookup(t.closeCtx, encodePubkey(key)).run() return t.newLookup(t.closeCtx, v4wire.EncodePubkey(key)).run()
} }
// RandomNodes is an iterator yielding nodes from a random walk of the DHT. // RandomNodes is an iterator yielding nodes from a random walk of the DHT.
@ -286,24 +286,24 @@ func (t *UDPv4) lookupRandom() []*enode.Node {
// lookupSelf implements transport. // lookupSelf implements transport.
func (t *UDPv4) lookupSelf() []*enode.Node { func (t *UDPv4) lookupSelf() []*enode.Node {
return t.newLookup(t.closeCtx, encodePubkey(&t.priv.PublicKey)).run() pubkey := v4wire.EncodePubkey(&t.priv.PublicKey)
return t.newLookup(t.closeCtx, pubkey).run()
} }
func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup { func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup {
var target encPubkey var target v4wire.Pubkey
crand.Read(target[:]) crand.Read(target[:])
return t.newLookup(ctx, target) return t.newLookup(ctx, target)
} }
func (t *UDPv4) newLookup(ctx context.Context, targetKey encPubkey) *lookup { func (t *UDPv4) newLookup(ctx context.Context, targetKey v4wire.Pubkey) *lookup {
target := enode.ID(crypto.Keccak256Hash(targetKey[:])) target := enode.ID(crypto.Keccak256Hash(targetKey[:]))
ekey := v4wire.Pubkey(targetKey)
it := newLookup(ctx, t.tab, target, func(n *enode.Node) ([]*enode.Node, error) { it := newLookup(ctx, t.tab, target, func(n *enode.Node) ([]*enode.Node, error) {
addr, ok := n.UDPEndpoint() addr, ok := n.UDPEndpoint()
if !ok { if !ok {
return nil, errNoUDPEndpoint return nil, errNoUDPEndpoint
} }
return t.findnode(n.ID(), addr, ekey) return t.findnode(n.ID(), addr, targetKey)
}) })
return it return it
} }

@ -314,7 +314,7 @@ func TestUDPv4_findnodeMultiReply(t *testing.T) {
// queue a pending findnode request // queue a pending findnode request
resultc, errc := make(chan []*enode.Node, 1), make(chan error, 1) resultc, errc := make(chan []*enode.Node, 1), make(chan error, 1)
go func() { go func() {
rid := encodePubkey(&test.remotekey.PublicKey).id() rid := v4wire.EncodePubkey(&test.remotekey.PublicKey).ID()
ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget) ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget)
if err != nil && len(ns) == 0 { if err != nil && len(ns) == 0 {
errc <- err errc <- err
@ -433,7 +433,7 @@ func TestUDPv4_successfulPing(t *testing.T) {
// pong packet. // pong packet.
select { select {
case n := <-added: case n := <-added:
rid := encodePubkey(&test.remotekey.PublicKey).id() rid := v4wire.EncodePubkey(&test.remotekey.PublicKey).ID()
if n.ID() != rid { if n.ID() != rid {
t.Errorf("node has wrong ID: got %v, want %v", n.ID(), rid) t.Errorf("node has wrong ID: got %v, want %v", n.ID(), rid)
} }

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/internal/testlog" "github.com/ethereum/go-ethereum/internal/testlog"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discover/v4wire"
"github.com/ethereum/go-ethereum/p2p/discover/v5wire" "github.com/ethereum/go-ethereum/p2p/discover/v5wire"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/p2p/enr"
@ -576,7 +577,7 @@ func TestUDPv5_lookup(t *testing.T) {
test := newUDPV5Test(t) test := newUDPV5Test(t)
// Lookup on empty table returns no nodes. // Lookup on empty table returns no nodes.
if results := test.udp.Lookup(lookupTestnet.target.id()); len(results) > 0 { if results := test.udp.Lookup(lookupTestnet.target.ID()); len(results) > 0 {
t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results) t.Fatalf("lookup on empty table returned %d results: %#v", len(results), results)
} }
@ -596,7 +597,7 @@ func TestUDPv5_lookup(t *testing.T) {
// Start the lookup. // Start the lookup.
resultC := make(chan []*enode.Node, 1) resultC := make(chan []*enode.Node, 1)
go func() { go func() {
resultC <- test.udp.Lookup(lookupTestnet.target.id()) resultC <- test.udp.Lookup(lookupTestnet.target.ID())
test.close() test.close()
}() }()
@ -793,7 +794,7 @@ func (test *udpV5Test) packetInFrom(key *ecdsa.PrivateKey, addr netip.AddrPort,
// getNode ensures the test knows about a node at the given endpoint. // getNode ensures the test knows about a node at the given endpoint.
func (test *udpV5Test) getNode(key *ecdsa.PrivateKey, addr netip.AddrPort) *enode.LocalNode { func (test *udpV5Test) getNode(key *ecdsa.PrivateKey, addr netip.AddrPort) *enode.LocalNode {
id := encodePubkey(&key.PublicKey).id() id := v4wire.EncodePubkey(&key.PublicKey).ID()
ln := test.nodesByID[id] ln := test.nodesByID[id]
if ln == nil { if ln == nil {
db, _ := enode.OpenDB("") db, _ := enode.OpenDB("")