p2p/discover: add support for EIP-868 (v4 ENR extension)

This change implements EIP-868. The UDPv4 transport announces support
for the extension in ping/pong and handles enrRequest messages.

There are two uses of the extension: If a remote node announces support
for EIP-868 in their pong, node revalidation pulls the node's record.
The Resolve method requests the record unconditionally.
This commit is contained in:
Felix Lange 2019-05-03 14:21:15 +02:00
parent d2e5d97671
commit aa470f8905
5 changed files with 331 additions and 78 deletions

View file

@ -62,6 +62,9 @@ const (
seedMaxAge = 5 * 24 * time.Hour seedMaxAge = 5 * 24 * time.Hour
) )
// Table is the 'node table', a Kademlia-like index of neighbor nodes. The table keeps
// itself up-to-date by verifying the liveness of neighbors and requesting their node
// records when announcements of a new record version are received.
type Table struct { type Table struct {
mutex sync.Mutex // protects buckets, bucket content, nursery, rand mutex sync.Mutex // protects buckets, bucket content, nursery, rand
buckets [nBuckets]*bucket // index of known nodes by distance buckets [nBuckets]*bucket // index of known nodes by distance
@ -80,12 +83,13 @@ type Table struct {
nodeAddedHook func(*node) // for testing nodeAddedHook func(*node) // for testing
} }
// transport is implemented by UDP transports. // transport is implemented by the UDP transports.
type transport interface { type transport interface {
Self() *enode.Node Self() *enode.Node
lookupRandom() []*enode.Node lookupRandom() []*enode.Node
lookupSelf() []*enode.Node lookupSelf() []*enode.Node
ping(*enode.Node) error ping(*enode.Node) (seq uint64, err error)
requestENR(*enode.Node) (*enode.Node, error)
} }
// bucket contains nodes, ordered by their last activity. the entry // bucket contains nodes, ordered by their last activity. the entry
@ -176,14 +180,16 @@ func (tab *Table) ReadRandomNodes(buf []*enode.Node) (n int) {
return i + 1 return i + 1
} }
// Resolve searches for a specific node with the given ID. // getNode returns the node with the given ID or nil if it isn't in the table.
// It returns nil if the node could not be found. func (tab *Table) getNode(id enode.ID) *enode.Node {
func (tab *Table) Resolve(n *enode.Node) *enode.Node {
tab.mutex.Lock() tab.mutex.Lock()
cl := tab.closest(n.ID(), 1, false) defer tab.mutex.Unlock()
tab.mutex.Unlock()
if len(cl.entries) > 0 && cl.entries[0].ID() == n.ID() { b := tab.bucket(id)
return unwrapNode(cl.entries[0]) for _, e := range b.entries {
if e.ID() == id {
return unwrapNode(e)
}
} }
return nil return nil
} }
@ -227,7 +233,7 @@ func (tab *Table) refresh() <-chan struct{} {
return done return done
} }
// loop schedules refresh, revalidate runs and coordinates shutdown. // loop schedules runs of doRefresh, doRevalidate and copyLiveNodes.
func (tab *Table) loop() { func (tab *Table) loop() {
var ( var (
revalidate = time.NewTimer(tab.nextRevalidateTime()) revalidate = time.NewTimer(tab.nextRevalidateTime())
@ -289,9 +295,8 @@ loop:
close(tab.closed) close(tab.closed)
} }
// doRefresh performs a lookup for a random target to keep buckets // doRefresh performs a lookup for a random target to keep buckets full. seed nodes are
// full. seed nodes are inserted if the table is empty (initial // inserted if the table is empty (initial bootstrap or discarded faulty peers).
// bootstrap or discarded faulty peers).
func (tab *Table) doRefresh(done chan struct{}) { func (tab *Table) doRefresh(done chan struct{}) {
defer close(done) defer close(done)
@ -325,8 +330,8 @@ func (tab *Table) loadSeedNodes() {
} }
} }
// doRevalidate checks that the last node in a random bucket is still live // doRevalidate checks that the last node in a random bucket is still live and replaces or
// and replaces or deletes the node if it isn't. // deletes the node if it isn't.
func (tab *Table) doRevalidate(done chan<- struct{}) { func (tab *Table) doRevalidate(done chan<- struct{}) {
defer func() { done <- struct{}{} }() defer func() { done <- struct{}{} }()
@ -337,7 +342,17 @@ func (tab *Table) doRevalidate(done chan<- struct{}) {
} }
// Ping the selected node and wait for a pong. // Ping the selected node and wait for a pong.
err := tab.net.ping(unwrapNode(last)) remoteSeq, err := tab.net.ping(unwrapNode(last))
// Also fetch record if the node replied and returned a higher sequence number.
if last.Seq() < remoteSeq {
n, err := tab.net.requestENR(unwrapNode(last))
if err != nil {
tab.log.Debug("ENR request failed", "id", last.ID(), "addr", last.addr(), "err", err)
} else {
last = &node{Node: *n, addedAt: last.addedAt, livenessChecks: last.livenessChecks}
}
}
tab.mutex.Lock() tab.mutex.Lock()
defer tab.mutex.Unlock() defer tab.mutex.Unlock()

View file

@ -368,6 +368,34 @@ func TestTable_addSeenNode(t *testing.T) {
checkIPLimitInvariant(t, tab) checkIPLimitInvariant(t, tab)
} }
// This test checks that ENR updates happen during revalidation. If a node in the table
// announces a new sequence number, the new record should be pulled.
func TestTable_revalidateSyncRecord(t *testing.T) {
transport := newPingRecorder()
tab, db := newTestTable(transport)
<-tab.initDone
defer db.Close()
defer tab.close()
// Insert a node.
var r enr.Record
r.Set(enr.IP(net.IP{127, 0, 0, 1}))
id := enode.ID{1}
n1 := wrapNode(enode.SignNull(&r, id))
tab.addSeenNode(n1)
// Update the node record.
r.Set(enr.WithEntry("foo", "bar"))
n2 := enode.SignNull(&r, id)
transport.updateRecord(n2)
tab.doRevalidate(make(chan struct{}, 1))
intable := tab.getNode(id)
if !reflect.DeepEqual(intable, n2) {
t.Fatalf("table contains old record with seq %d, want seq %d", intable.Seq(), n2.Seq())
}
}
// gen wraps quick.Value so it's easier to use. // gen wraps quick.Value so it's easier to use.
// it generates a random value of the given value's type. // it generates a random value of the given value's type.
func gen(typ interface{}, rand *rand.Rand) interface{} { func gen(typ interface{}, rand *rand.Rand) interface{} {

View file

@ -97,6 +97,7 @@ func fillTable(tab *Table, nodes []*node) {
type pingRecorder struct { type pingRecorder struct {
mu sync.Mutex mu sync.Mutex
dead, pinged map[enode.ID]bool dead, pinged map[enode.ID]bool
records map[enode.ID]*enode.Node
n *enode.Node n *enode.Node
} }
@ -108,36 +109,51 @@ func newPingRecorder() *pingRecorder {
return &pingRecorder{ return &pingRecorder{
dead: make(map[enode.ID]bool), dead: make(map[enode.ID]bool),
pinged: make(map[enode.ID]bool), pinged: make(map[enode.ID]bool),
records: make(map[enode.ID]*enode.Node),
n: n, n: n,
} }
} }
func (t *pingRecorder) Self() *enode.Node { // setRecord updates a node record. Future calls to ping and
return nullNode // requestENR will return this record.
func (t *pingRecorder) updateRecord(n *enode.Node) {
t.mu.Lock()
defer t.mu.Unlock()
t.records[n.ID()] = n
} }
func (t *pingRecorder) ping(n *enode.Node) error { // Stubs to satisfy the transport interface.
func (t *pingRecorder) Self() *enode.Node { return nullNode }
func (t *pingRecorder) lookupSelf() []*enode.Node { return nil }
func (t *pingRecorder) lookupRandom() []*enode.Node { return nil }
func (t *pingRecorder) close() {}
// ping simulates a ping request.
func (t *pingRecorder) ping(n *enode.Node) (seq uint64, err error) {
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
t.pinged[n.ID()] = true t.pinged[n.ID()] = true
if t.dead[n.ID()] { if t.dead[n.ID()] {
return errTimeout return 0, errTimeout
} else {
return nil
} }
if t.records[n.ID()] != nil {
seq = t.records[n.ID()].Seq()
}
return seq, nil
} }
func (t *pingRecorder) lookupSelf() []*enode.Node { // requestENR simulates an ENR request.
return nil func (t *pingRecorder) requestENR(n *enode.Node) (*enode.Node, error) {
} t.mu.Lock()
defer t.mu.Unlock()
func (t *pingRecorder) lookupRandom() []*enode.Node { if t.dead[n.ID()] || t.records[n.ID()] == nil {
return nil return nil, errTimeout
}
return t.records[n.ID()], nil
} }
func (t *pingRecorder) close() {}
func hasDuplicates(slice []*node) bool { func hasDuplicates(slice []*node) bool {
seen := make(map[enode.ID]bool) seen := make(map[enode.ID]bool)
for i, e := range slice { for i, e := range slice {

View file

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"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/netutil" "github.com/ethereum/go-ethereum/p2p/netutil"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
@ -69,6 +70,8 @@ const (
p_pongV4 p_pongV4
p_findnodeV4 p_findnodeV4
p_neighborsV4 p_neighborsV4
p_enrRequestV4
p_enrResponseV4
) )
// RPC request structures // RPC request structures
@ -112,6 +115,21 @@ type (
Rest []rlp.RawValue `rlp:"tail"` Rest []rlp.RawValue `rlp:"tail"`
} }
// enrRequestV4 queries for the remote node's record.
enrRequestV4 struct {
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// enrResponseV4 is the reply to enrRequestV4.
enrResponseV4 struct {
ReplyTok []byte // Hash of the enrRequest packet.
Record enr.Record
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
rpcNode struct { rpcNode struct {
IP net.IP // len 4 for IPv4 or 16 for IPv6 IP net.IP // len 4 for IPv4 or 16 for IPv6
UDP uint16 // for discovery protocol UDP uint16 // for discovery protocol
@ -218,7 +236,11 @@ type replyMatcher struct {
// errc receives nil when the callback indicates completion or an // errc receives nil when the callback indicates completion or an
// error if no further reply is received within the timeout. // error if no further reply is received within the timeout.
errc chan<- error errc chan error
// reply contains the most recent reply. This field is safe for reading after errc has
// received a value.
reply packetV4
} }
type replyMatchFunc func(interface{}) (matched bool, requestDone bool) type replyMatchFunc func(interface{}) (matched bool, requestDone bool)
@ -376,7 +398,8 @@ func (t *UDPv4) lookupWorker(n *node, targetKey encPubkey, reply chan<- []*node)
t.tab.delete(n) t.tab.delete(n)
} }
} else if fails > 0 { } else if fails > 0 {
t.db.UpdateFindFails(n.ID(), n.IP(), fails-1) // Reset failure counter because it counts _consecutive_ failures.
t.db.UpdateFindFails(n.ID(), n.IP(), 0)
} }
// Grab as many nodes as possible. Some of them might not be alive anymore, but we'll // Grab as many nodes as possible. Some of them might not be alive anymore, but we'll
@ -387,23 +410,34 @@ func (t *UDPv4) lookupWorker(n *node, targetKey encPubkey, reply chan<- []*node)
reply <- r reply <- r
} }
// Resolve searches for a specific node with the given ID. // Resolve searches for a specific node with the given ID and tries to get the most recent
// It returns nil if the node could not be found. // version of the node record for it. It returns n if the node could not be resolved.
func (t *UDPv4) Resolve(n *enode.Node) *enode.Node { func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
// If the node is present in the local table, no // Try asking directly. This works if the node is still responding on the endpoint we have.
// network interaction is required. if rn, err := t.requestENR(n); err == nil {
if intab := t.tab.Resolve(n); intab != nil { return rn
return intab }
// Check table for the ID, we might have a newer version there.
if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
n = intable
if rn, err := t.requestENR(n); err == nil {
return rn
}
}
// Otherwise perform a network lookup.
var key *enode.Secp256k1
if n.Load(key) != nil {
return n // no secp256k1 key
}
result := t.LookupPubkey((*ecdsa.PublicKey)(key))
for _, rn := range result {
if rn.ID() == n.ID() {
if rn, err := t.requestENR(rn); err == nil {
return rn
}
}
} }
// Otherwise, do a network lookup.
hash := n.ID()
result := t.LookupPubkey(n.Pubkey())
for _, n := range result {
if n.ID() == hash {
return n return n
}
}
return nil
} }
func (t *UDPv4) ourEndpoint() rpcEndpoint { func (t *UDPv4) ourEndpoint() rpcEndpoint {
@ -413,28 +447,27 @@ func (t *UDPv4) ourEndpoint() rpcEndpoint {
} }
// ping sends a ping message to the given node and waits for a reply. // ping sends a ping message to the given node and waits for a reply.
func (t *UDPv4) ping(n *enode.Node) error { func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
return <-t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil) rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
if err = <-rm.errc; err == nil {
seq = seqFromTail(rm.reply.(*pongV4).Rest)
}
return seq, err
} }
// sendPing sends a ping message to the given node and invokes the callback // sendPing sends a ping message to the given node and invokes the callback
// when the reply arrives. // when the reply arrives.
func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) <-chan error { func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
req := &pingV4{ req := t.makePing(toaddr)
Version: 4,
From: t.ourEndpoint(),
To: makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := t.encode(t.priv, req) packet, hash, err := t.encode(t.priv, req)
if err != nil { if err != nil {
errc := make(chan error, 1) errc := make(chan error, 1)
errc <- err errc <- err
return errc return &replyMatcher{errc: errc}
} }
// Add a matcher for the reply to the pending reply queue. Pongs are matched if they // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
// reference the ping we're about to send. // reference the ping we're about to send.
errc := t.pending(toid, toaddr.IP, p_pongV4, func(p interface{}) (matched bool, requestDone bool) { rm := t.pending(toid, toaddr.IP, p_pongV4, func(p interface{}) (matched bool, requestDone bool) {
matched = bytes.Equal(p.(*pongV4).ReplyTok, hash) matched = bytes.Equal(p.(*pongV4).ReplyTok, hash)
if matched && callback != nil { if matched && callback != nil {
callback() callback()
@ -444,25 +477,30 @@ func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) <-
// Send the packet. // Send the packet.
t.localNode.UDPContact(toaddr) t.localNode.UDPContact(toaddr)
t.write(toaddr, toid, req.name(), packet) t.write(toaddr, toid, req.name(), packet)
return errc return rm
}
func (t *UDPv4) makePing(toaddr *net.UDPAddr) *pingV4 {
seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
return &pingV4{
Version: 4,
From: t.ourEndpoint(),
To: makeEndpoint(toaddr, 0),
Expiration: uint64(time.Now().Add(expiration).Unix()),
Rest: []rlp.RawValue{seq},
}
} }
// findnode sends a findnode request to the given node and waits until // findnode sends a findnode request to the given node and waits until
// the node has sent up to k neighbors. // the node has sent up to k neighbors.
func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) { func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
// If we haven't seen a ping from the destination node for a while, it won't remember t.ensureBond(toid, toaddr)
// our endpoint proof and reject findnode. Solicit a ping first.
if time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration {
<-t.sendPing(toid, toaddr, nil)
// Wait for them to ping back and process our pong.
time.Sleep(respTimeout)
}
// Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is // Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
// active until enough nodes have been received. // active until enough nodes have been received.
nodes := make([]*node, 0, bucketSize) nodes := make([]*node, 0, bucketSize)
nreceived := 0 nreceived := 0
errc := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) { rm := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) {
reply := r.(*neighborsV4) reply := r.(*neighborsV4)
for _, rn := range reply.Nodes { for _, rn := range reply.Nodes {
nreceived++ nreceived++
@ -479,12 +517,49 @@ func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) (
Target: target, Target: target,
Expiration: uint64(time.Now().Add(expiration).Unix()), Expiration: uint64(time.Now().Add(expiration).Unix()),
}) })
return nodes, <-errc return nodes, <-rm.errc
}
// requestENR sends enrRequest to the given node and waits for a response.
func (t *UDPv4) requestENR(n *enode.Node) (*enode.Node, error) {
addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
t.ensureBond(n.ID(), addr)
req := &enrRequestV4{
Expiration: uint64(time.Now().Add(expiration).Unix()),
}
packet, hash, err := t.encode(t.priv, req)
if err != nil {
return nil, err
}
// Add a matcher for the reply to the pending reply queue. Responses are matched if
// they reference the request we're about to send.
rm := t.pending(n.ID(), addr.IP, p_enrResponseV4, func(r interface{}) (matched bool, requestDone bool) {
matched = bytes.Equal(r.(*enrResponseV4).ReplyTok, hash)
return matched, matched
})
// Send the packet and wait for the reply.
t.write(addr, n.ID(), req.name(), packet)
if err := <-rm.errc; err != nil {
return nil, err
}
// Verify the response record.
respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*enrResponseV4).Record)
if err != nil {
return nil, err
}
if respN.ID() != n.ID() {
return nil, fmt.Errorf("invalid ID in response record")
}
if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
return nil, fmt.Errorf("invalid IP in response record: %v", err)
}
return respN, nil
} }
// pending adds a reply matcher to the pending reply queue. // pending adds a reply matcher to the pending reply queue.
// see the documentation of type replyMatcher for a detailed explanation. // see the documentation of type replyMatcher for a detailed explanation.
func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) <-chan error { func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
ch := make(chan error, 1) ch := make(chan error, 1)
p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch} p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
select { select {
@ -493,7 +568,7 @@ func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchF
case <-t.closing: case <-t.closing:
ch <- errClosed ch <- errClosed
} }
return ch return p
} }
// handleReply dispatches a reply packet, invoking reply matchers. It returns // handleReply dispatches a reply packet, invoking reply matchers. It returns
@ -569,6 +644,7 @@ func (t *UDPv4) loop() {
matched = matched || ok matched = matched || ok
// Remove the matcher if callback indicates that all replies have been received. // Remove the matcher if callback indicates that all replies have been received.
if requestDone { if requestDone {
p.reply = r.data
p.errc <- nil p.errc <- nil
plist.Remove(el) plist.Remove(el)
} }
@ -743,6 +819,10 @@ func decodeV4(buf []byte) (packetV4, encPubkey, []byte, error) {
req = new(findnodeV4) req = new(findnodeV4)
case p_neighborsV4: case p_neighborsV4:
req = new(neighborsV4) req = new(neighborsV4)
case p_enrRequestV4:
req = new(enrRequestV4)
case p_enrResponseV4:
req = new(enrResponseV4)
default: default:
return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype) return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype)
} }
@ -751,7 +831,38 @@ func decodeV4(buf []byte) (packetV4, encPubkey, []byte, error) {
return req, fromKey, hash, err return req, fromKey, hash, err
} }
// Packet Handlers // checkBond checks if the given node has a recent enough endpoint proof.
func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
}
// ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
// This ensures there is a valid endpoint proof on the remote end.
func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
if tooOld || t.db.FindFails(toid, toaddr.IP) > 5 {
rm := t.sendPing(toid, toaddr, nil)
<-rm.errc
// Wait for them to ping back and process our pong.
time.Sleep(respTimeout)
}
}
// expired checks whether the given UNIX time stamp is in the past.
func expired(ts uint64) bool {
return time.Unix(int64(ts), 0).Before(time.Now())
}
func seqFromTail(tail []rlp.RawValue) uint64 {
if len(tail) == 0 {
return 0
}
var seq uint64
rlp.DecodeBytes(tail[0], &seq)
return seq
}
// PING/v4
func (req *pingV4) name() string { return "PING/v4" } func (req *pingV4) name() string { return "PING/v4" }
func (req *pingV4) kind() byte { return p_pingV4 } func (req *pingV4) kind() byte { return p_pingV4 }
@ -770,10 +881,12 @@ func (req *pingV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromK
func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) { func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
// Reply. // Reply.
seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
t.send(from, fromID, &pongV4{ t.send(from, fromID, &pongV4{
To: makeEndpoint(from, req.From.TCP), To: makeEndpoint(from, req.From.TCP),
ReplyTok: mac, ReplyTok: mac,
Expiration: uint64(time.Now().Add(expiration).Unix()), Expiration: uint64(time.Now().Add(expiration).Unix()),
Rest: []rlp.RawValue{seq},
}) })
// Ping back if our last pong on file is too far in the past. // Ping back if our last pong on file is too far in the past.
@ -791,6 +904,8 @@ func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []by
t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)}) t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
} }
// PONG/v4
func (req *pongV4) name() string { return "PONG/v4" } func (req *pongV4) name() string { return "PONG/v4" }
func (req *pongV4) kind() byte { return p_pongV4 } func (req *pongV4) kind() byte { return p_pongV4 }
@ -809,6 +924,8 @@ func (req *pongV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []by
t.db.UpdateLastPongReceived(fromID, from.IP, time.Now()) t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
} }
// FINDNODE/v4
func (req *findnodeV4) name() string { return "FINDNODE/v4" } func (req *findnodeV4) name() string { return "FINDNODE/v4" }
func (req *findnodeV4) kind() byte { return p_findnodeV4 } func (req *findnodeV4) kind() byte { return p_findnodeV4 }
@ -816,7 +933,7 @@ func (req *findnodeV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, f
if expired(req.Expiration) { if expired(req.Expiration) {
return errExpired return errExpired
} }
if time.Since(t.db.LastPongReceived(fromID, from.IP)) > bondExpiration { if !t.checkBond(fromID, from.IP) {
// No endpoint proof pong exists, we don't process the packet. This prevents an // No endpoint proof pong exists, we don't process the packet. This prevents an
// attack vector where the discovery protocol could be used to amplify traffic in a // attack vector where the discovery protocol could be used to amplify traffic in a
// DDOS attack. A malicious actor would send a findnode request with the IP address // DDOS attack. A malicious actor would send a findnode request with the IP address
@ -854,6 +971,8 @@ func (req *findnodeV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac
} }
} }
// NEIGHBORS/v4
func (req *neighborsV4) name() string { return "NEIGHBORS/v4" } func (req *neighborsV4) name() string { return "NEIGHBORS/v4" }
func (req *neighborsV4) kind() byte { return p_neighborsV4 } func (req *neighborsV4) kind() byte { return p_neighborsV4 }
@ -870,6 +989,39 @@ func (req *neighborsV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID,
func (req *neighborsV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) { func (req *neighborsV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
} }
func expired(ts uint64) bool { // ENRREQUEST/v4
return time.Unix(int64(ts), 0).Before(time.Now())
func (req *enrRequestV4) name() string { return "ENRREQUEST/v4" }
func (req *enrRequestV4) kind() byte { return p_enrRequestV4 }
func (req *enrRequestV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) {
return errExpired
}
if !t.checkBond(fromID, from.IP) {
return errUnknownNode
}
return nil
}
func (req *enrRequestV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
t.send(from, fromID, &enrResponseV4{
ReplyTok: mac,
Record: *t.localNode.Node().Record(),
})
}
// ENRRESPONSE/v4
func (req *enrResponseV4) name() string { return "ENRRESPONSE/v4" }
func (req *enrResponseV4) kind() byte { return p_enrResponseV4 }
func (req *enrResponseV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if !t.handleReply(fromID, from.IP, req) {
return errUnsolicitedReply
}
return nil
}
func (req *enrResponseV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
} }

View file

@ -37,6 +37,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/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
@ -153,7 +154,7 @@ func TestUDPv4_pingTimeout(t *testing.T) {
key := newkey() key := newkey()
toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222} toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
node := enode.NewV4(&key.PublicKey, toaddr.IP, 0, toaddr.Port) node := enode.NewV4(&key.PublicKey, toaddr.IP, 0, toaddr.Port)
if err := test.udp.ping(node); err != errTimeout { if _, err := test.udp.ping(node); err != errTimeout {
t.Error("expected timeout error, got", err) t.Error("expected timeout error, got", err)
} }
} }
@ -367,6 +368,7 @@ func TestUDPv4_findnodeMultiReply(t *testing.T) {
} }
} }
// This test checks that reply matching of pong verifies the ping hash.
func TestUDPv4_pingMatch(t *testing.T) { func TestUDPv4_pingMatch(t *testing.T) {
test := newUDPTest(t) test := newUDPTest(t)
defer test.close() defer test.close()
@ -380,6 +382,7 @@ func TestUDPv4_pingMatch(t *testing.T) {
test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: randToken, To: testLocalAnnounced, Expiration: futureExp}) test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: randToken, To: testLocalAnnounced, Expiration: futureExp})
} }
// This test checks that reply matching of pong verifies the sender IP address.
func TestUDPv4_pingMatchIP(t *testing.T) { func TestUDPv4_pingMatchIP(t *testing.T) {
test := newUDPTest(t) test := newUDPTest(t)
defer test.close() defer test.close()
@ -406,7 +409,7 @@ func TestUDPv4_successfulPing(t *testing.T) {
// The remote side sends a ping packet to initiate the exchange. // The remote side sends a ping packet to initiate the exchange.
go test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp}) go test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
// the ping is replied to. // The ping is replied to.
test.waitPacketOut(func(p *pongV4, to *net.UDPAddr, hash []byte) { test.waitPacketOut(func(p *pongV4, to *net.UDPAddr, hash []byte) {
pinghash := test.sent[0][:macSize] pinghash := test.sent[0][:macSize]
if !bytes.Equal(p.ReplyTok, pinghash) { if !bytes.Equal(p.ReplyTok, pinghash) {
@ -423,7 +426,7 @@ func TestUDPv4_successfulPing(t *testing.T) {
} }
}) })
// remote is unknown, the table pings back. // Remote is unknown, the table pings back.
test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) { test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) {
if !reflect.DeepEqual(p.From, test.udp.ourEndpoint()) { if !reflect.DeepEqual(p.From, test.udp.ourEndpoint()) {
t.Errorf("got ping.From %#v, want %#v", p.From, test.udp.ourEndpoint()) t.Errorf("got ping.From %#v, want %#v", p.From, test.udp.ourEndpoint())
@ -440,7 +443,7 @@ func TestUDPv4_successfulPing(t *testing.T) {
test.packetIn(nil, &pongV4{ReplyTok: hash, Expiration: futureExp}) test.packetIn(nil, &pongV4{ReplyTok: hash, Expiration: futureExp})
}) })
// the node should be added to the table shortly after getting the // The node should be added to the table shortly after getting the
// pong packet. // pong packet.
select { select {
case n := <-added: case n := <-added:
@ -462,6 +465,45 @@ func TestUDPv4_successfulPing(t *testing.T) {
} }
} }
// This test checks that EIP-868 requests work.
func TestUDPv4_EIP868(t *testing.T) {
test := newUDPTest(t)
defer test.close()
test.udp.localNode.Set(enr.WithEntry("foo", "bar"))
wantNode := test.udp.localNode.Node()
// ENR requests aren't allowed before endpoint proof.
test.packetIn(errUnknownNode, &enrRequestV4{Expiration: futureExp})
// Perform endpoint proof and check for sequence number in packet tail.
test.packetIn(nil, &pingV4{Expiration: futureExp})
test.waitPacketOut(func(p *pongV4, addr *net.UDPAddr, hash []byte) {
if seq := seqFromTail(p.Rest); seq != wantNode.Seq() {
t.Errorf("wrong sequence number in pong: %d, want %d", seq, wantNode.Seq())
}
})
test.waitPacketOut(func(p *pingV4, addr *net.UDPAddr, hash []byte) {
if seq := seqFromTail(p.Rest); seq != wantNode.Seq() {
t.Errorf("wrong sequence number in ping: %d, want %d", seq, wantNode.Seq())
}
test.packetIn(nil, &pongV4{Expiration: futureExp, ReplyTok: hash})
})
// Request should work now.
test.packetIn(nil, &enrRequestV4{Expiration: futureExp})
test.waitPacketOut(func(p *enrResponseV4, addr *net.UDPAddr, hash []byte) {
n, err := enode.New(enode.ValidSchemes, &p.Record)
if err != nil {
t.Fatalf("invalid record: %v", err)
}
if !reflect.DeepEqual(n, wantNode) {
t.Fatalf("wrong node in enrResponse: %v", n)
}
})
}
// EIP-8 test vectors.
var testPackets = []struct { var testPackets = []struct {
input string input string
wantPacket interface{} wantPacket interface{}