Skip to content

Commit a67f68d

Browse files
committed
feat(eth): wake xdc/166 request consumers when a peer exits ethereum#23576, ref #3027
1 parent c1119a8 commit a67f68d

8 files changed

Lines changed: 350 additions & 55 deletions

File tree

‎eth/downloader/downloader.go‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -390,17 +390,19 @@ func (d *Downloader) RegisterPeer(id string, version uint, peer Peer) error {
390390

391391
// deliverPack routes a xdc/166 response packet back into the same channel the
392392
// node layer uses for legacy replies, preserving the delivery meters and the
393-
// cancellation/backpressure behaviour of Downloader.deliver.
394-
func (d *Downloader) deliverPack(packet dataPack) error {
393+
// cancellation/backpressure behaviour of Downloader.deliver. The cancel channel
394+
// is the one captured when the request was issued, so a reply cannot leak into
395+
// a later sync's shared delivery channel.
396+
func (d *Downloader) deliverPack(packet dataPack, cancel <-chan struct{}) error {
395397
switch pack := packet.(type) {
396398
case *headerPack:
397-
return d.deliver(pack.peerId, d.headerCh, pack, headerInMeter, headerDropMeter)
399+
return d.deliverWithCancel(pack.peerId, d.headerCh, pack, headerInMeter, headerDropMeter, cancel)
398400
case *bodyPack:
399-
return d.deliver(pack.peerId, d.bodyCh, pack, bodyInMeter, bodyDropMeter)
401+
return d.deliverWithCancel(pack.peerId, d.bodyCh, pack, bodyInMeter, bodyDropMeter, cancel)
400402
case *receiptPack:
401-
return d.deliver(pack.peerId, d.receiptCh, pack, receiptInMeter, receiptDropMeter)
403+
return d.deliverWithCancel(pack.peerId, d.receiptCh, pack, receiptInMeter, receiptDropMeter, cancel)
402404
case *statePack:
403-
return d.deliver(pack.peerId, d.stateCh, pack, stateInMeter, stateDropMeter)
405+
return d.deliverWithCancel(pack.peerId, d.stateCh, pack, stateInMeter, stateDropMeter, cancel)
404406
default:
405407
return fmt.Errorf("unknown data pack %T", packet)
406408
}
@@ -2350,21 +2352,37 @@ func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) {
23502352

23512353
// deliver injects a new batch of data received from a remote node.
23522354
func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter *metrics.Meter) (err error) {
2355+
d.cancelLock.RLock()
2356+
cancel := d.cancelCh
2357+
d.cancelLock.RUnlock()
2358+
2359+
return d.deliverWithCancel(id, destCh, packet, inMeter, dropMeter, cancel)
2360+
}
2361+
2362+
// deliverWithCancel injects a packet into destCh, aborting if the sync that
2363+
// issued the request was cancelled while queuing. The cancel channel is passed
2364+
// in so a xdc/166 reply is judged against the sync that issued it, not against
2365+
// whatever sync happens to be running when the reply arrives.
2366+
func (d *Downloader) deliverWithCancel(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter *metrics.Meter, cancel <-chan struct{}) (err error) {
23532367
// Update the delivery metrics for both good and failed deliveries
23542368
inMeter.Mark(int64(packet.Items()))
23552369
defer func() {
23562370
if err != nil {
23572371
dropMeter.Mark(int64(packet.Items()))
23582372
}
23592373
}()
2360-
// Deliver or abort if the sync is canceled while queuing
2361-
d.cancelLock.RLock()
2362-
cancel := d.cancelCh
2363-
d.cancelLock.RUnlock()
2374+
// Deliver or abort if the sync is canceled while queuing. Check the
2375+
// cancellation first: a closed channel and a free slot are both ready for
2376+
// select, and a reply from a cancelled sync must never be delivered.
23642377
if cancel == nil {
23652378
return errNoSyncActive
23662379
}
23672380
select {
2381+
case <-cancel:
2382+
return errNoSyncActive
2383+
default:
2384+
}
2385+
select {
23682386
case destCh <- packet:
23692387
return nil
23702388
case <-cancel:

‎eth/downloader/peer.go‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@ type peerConnection struct {
7474

7575
peer Peer
7676

77-
deliver func(dataPack) error // Injects xdc/166 responses into the downloader queue
78-
cancel func() <-chan struct{} // Current sync cancellation channel
77+
deliver func(dataPack, <-chan struct{}) error // Injects xdc/166 responses into the downloader queue
78+
cancel func() <-chan struct{} // Current sync cancellation channel
7979

8080
version uint // Eth protocol version number to switch strategies
8181
log log.Logger // Contextual logger to add extra infos to peer logs
@@ -132,7 +132,7 @@ func shortPeerID(id string) string {
132132
// newPeerConnection creates a new downloader peer. The deliver and cancel
133133
// callbacks bridge xdc/166 request sinks back into the downloader; they are
134134
// unused by the legacy request path.
135-
func newPeerConnection(id string, version uint, peer Peer, logger log.Logger, deliver func(dataPack) error, cancel func() <-chan struct{}) *peerConnection {
135+
func newPeerConnection(id string, version uint, peer Peer, logger log.Logger, deliver func(dataPack, <-chan struct{}) error, cancel func() <-chan struct{}) *peerConnection {
136136
return &peerConnection{
137137
id: id,
138138
lacking: make(map[common.Hash]struct{}),
@@ -318,17 +318,29 @@ func (p *peerConnection) waitResponse(req *eth.Request, resCh chan *eth.Response
318318
}
319319
defer req.Close()
320320

321+
// Capture the cancellation channel of the sync that issued the request: the
322+
// reply belongs to that sync and must not be delivered into a later sync's
323+
// shared channel.
324+
cancel := p.cancelChannel()
325+
321326
select {
322327
case res := <-resCh:
323328
if res == nil {
324329
return
325330
}
326331
var err error
327332
if p.deliver != nil {
328-
err = p.deliver(pack(res))
333+
err = p.deliver(pack(res), cancel)
334+
}
335+
// A cancelled sync is a local condition, not a peer fault: acknowledge
336+
// it so the reader keeps the connection instead of disconnecting an
337+
// honest peer.
338+
if errors.Is(err, errNoSyncActive) {
339+
err = nil
329340
}
330341
res.Done <- err
331-
case <-p.cancelChannel():
342+
case <-req.Terminated():
343+
case <-cancel:
332344
}
333345
}
334346

‎eth/downloader/peer_test.go‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func TestWaitResponseAcknowledgesDeliveryError(t *testing.T) {
3737
}
3838
resCh <- res
3939

40-
p := &peerConnection{deliver: func(dataPack) error { return deliverErr }}
40+
p := &peerConnection{deliver: func(dataPack, <-chan struct{}) error { return deliverErr }}
4141
p.waitResponse(&eth.Request{}, resCh, func(*eth.Response) dataPack { return &headerPack{} })
4242

4343
select {
@@ -50,6 +50,60 @@ func TestWaitResponseAcknowledgesDeliveryError(t *testing.T) {
5050
}
5151
}
5252

53+
// TestWaitResponseAcknowledgesLocalCancel checks that a delivery aborted by a
54+
// cancelled sync is acknowledged with nil instead of disconnecting the peer,
55+
// which did nothing wrong.
56+
func TestWaitResponseAcknowledgesLocalCancel(t *testing.T) {
57+
resCh := make(chan *eth.Response, 1)
58+
res := &eth.Response{
59+
Res: &eth.BlockHeadersPacket{},
60+
Done: make(chan error, 1),
61+
}
62+
resCh <- res
63+
64+
p := &peerConnection{deliver: func(dataPack, <-chan struct{}) error { return errNoSyncActive }}
65+
p.waitResponse(&eth.Request{}, resCh, func(*eth.Response) dataPack { return &headerPack{} })
66+
67+
select {
68+
case err := <-res.Done:
69+
if err != nil {
70+
t.Fatalf("Done verdict: have %v, want nil", err)
71+
}
72+
default:
73+
t.Fatal("response was not acknowledged on Done")
74+
}
75+
}
76+
77+
// TestDeliverWithCancelRejectsCancelledSync checks that a reply is judged
78+
// against the sync that issued its request: once that sync is cancelled the
79+
// packet must not enter the shared delivery channel, even while a newer sync is
80+
// already running.
81+
func TestDeliverWithCancelRejectsCancelledSync(t *testing.T) {
82+
// A newer sync is already running: its channel must not admit the packet.
83+
d := &Downloader{headerCh: make(chan dataPack, 1), cancelCh: make(chan struct{})}
84+
85+
cancelled := make(chan struct{})
86+
close(cancelled)
87+
if err := d.deliverWithCancel("peer", d.headerCh, &headerPack{peerId: "peer"}, headerInMeter, headerDropMeter, cancelled); !errors.Is(err, errNoSyncActive) {
88+
t.Fatalf("delivery from a cancelled sync: have %v, want %v", err, errNoSyncActive)
89+
}
90+
select {
91+
case packet := <-d.headerCh:
92+
t.Fatalf("packet from a cancelled sync was delivered: %v", packet)
93+
default:
94+
}
95+
// The same packet must go through while the issuing sync is still live.
96+
live := make(chan struct{})
97+
if err := d.deliverWithCancel("peer", d.headerCh, &headerPack{peerId: "peer"}, headerInMeter, headerDropMeter, live); err != nil {
98+
t.Fatalf("delivery from a live sync failed: %v", err)
99+
}
100+
select {
101+
case <-d.headerCh:
102+
default:
103+
t.Fatal("packet from a live sync was not delivered")
104+
}
105+
}
106+
53107
// TestIdlePeersProtocolVersions verifies that peers running every supported
54108
// protocol version (xdc100, xdc164, xdc165, xdc166) are eligible for concurrent
55109
// downloads. A regression here silently disables skeleton filling and body,

‎eth/fetcher/block_fetcher.go‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ const (
4040
fetchTimeout = 5 * time.Second // Maximum allotted time to return an explicitly requested block/transaction
4141
)
4242

43+
// fetchResponseTimeout bounds how long an explicitly requested block part may
44+
// stay unanswered. It is 2x fetchTimeout to leave room for a catchup after the
45+
// announce itself already expired; a peer that still does not answer is dropped
46+
// as a protocol violation. Tests shorten it to keep their runtime bounded.
47+
var fetchResponseTimeout = 2 * fetchTimeout
48+
4349
const (
4450
maxUncleDist = 7 // Maximum allowed backward distance from the chain head
4551
maxQueueDist = 32 // Maximum allowed distance from the chain head to queue
@@ -332,6 +338,30 @@ func (f *BlockFetcher) Enqueue(peer string, block *types.Block) error {
332338
}
333339
}
334340

341+
// waitResponse waits for the reply of an explicitly requested block part. It
342+
// reports false if the request was abandoned: the peer went away, the fetcher
343+
// stopped, or the peer did not answer in time and was dropped. No response was
344+
// taken on those paths, so the caller owes no Done verdict; its deferred
345+
// Request.Close releases the dispatcher entry either way.
346+
func (f *BlockFetcher) waitResponse(peer string, req *eth.Request, resCh chan *eth.Response) (*eth.Response, bool) {
347+
timeout := time.NewTimer(fetchResponseTimeout)
348+
defer timeout.Stop()
349+
350+
select {
351+
case res := <-resCh:
352+
return res, true
353+
case <-req.Terminated():
354+
return nil, false
355+
case <-timeout.C:
356+
// The peer advertised the block and then did not serve it. The hash was
357+
// already rescheduled, so an unresponsive peer is a protocol violation.
358+
f.dropPeer(peer)
359+
return nil, false
360+
case <-f.quit:
361+
return nil, false
362+
}
363+
}
364+
335365
// FilterHeaders extracts all the headers that were explicitly requested by the fetcher,
336366
// returning those that should be handled differently.
337367
func (f *BlockFetcher) FilterHeaders(peer string, headers []*types.Header, time time.Time) []*types.Header {
@@ -519,12 +549,16 @@ func (f *BlockFetcher) loop() {
519549
}
520550
defer req.Close()
521551

522-
res := <-resCh
523-
if res == nil {
552+
res, ok := f.waitResponse(peer, req, resCh)
553+
if !ok || res == nil {
524554
return
525555
}
526556
res.Done <- nil
527-
f.FilterHeaders(peer, *res.Res.(*eth.BlockHeadersPacket), time.Now().Add(res.Time))
557+
// xdc/166 replies are matched by request id, so the
558+
// leftovers are dropped on purpose: the legacy hand-off
559+
// fed them to the downloader, which cannot tell them
560+
// apart from a reply to its own request.
561+
f.FilterHeaders(peer, *res.Res.(*eth.BlockHeadersPacket), time.Now())
528562
}(hash)
529563
}
530564
}(peer)
@@ -570,12 +604,14 @@ func (f *BlockFetcher) loop() {
570604
}
571605
defer req.Close()
572606

573-
res := <-resCh
574-
if res == nil {
607+
res, ok := f.waitResponse(peer, req, resCh)
608+
if !ok || res == nil {
575609
return
576610
}
577611
res.Done <- nil
578612
txs, uncles := res.Res.(*eth.BlockBodiesPacket).Unpack()
613+
// Leftovers are dropped for the same reason as the header
614+
// path above.
579615
f.FilterBodies(peer, txs, uncles, time.Now())
580616
}(peer, hashes)
581617
}

‎eth/fetcher/block_fetcher_test.go‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,110 @@ func TestAnnouncedBlockFetchedThroughSink(t *testing.T) {
679679
}
680680
}
681681

682+
// TestFilterHeadersIgnoresResponseDuration checks that the header filter uses
683+
// the receive time, not the round trip added to it: a large response duration
684+
// must not stamp the imported block with a time in the future.
685+
func TestFilterHeadersIgnoresResponseDuration(t *testing.T) {
686+
hashes, blocks := makeChain(2, 0, genesis)
687+
688+
// Start from a tester whose head is block 1, so the empty block 2 can be
689+
// imported as soon as its header arrives. makeChain returns its hashes in
690+
// reverse order: hashes[0] is the newest block.
691+
tester := newIdleTester()
692+
tester.hashes = append(tester.hashes, hashes[1])
693+
tester.blocks[hashes[1]] = blocks[hashes[1]]
694+
tester.fetcher.Start()
695+
t.Cleanup(tester.fetcher.Stop)
696+
697+
headerFetcher := func(hash common.Hash, sink chan *eth.Response) (*eth.Request, error) {
698+
headers := eth.BlockHeadersPacket{blocks[hash].Header()}
699+
go func() {
700+
sink <- &eth.Response{Res: &headers, Time: 30 * time.Second, Done: make(chan error, 1)}
701+
}()
702+
return &eth.Request{}, nil
703+
}
704+
bodyFetcher := func(hashes []common.Hash, sink chan *eth.Response) (*eth.Request, error) {
705+
return &eth.Request{}, nil
706+
}
707+
imported := make(chan *types.Block)
708+
tester.watchImports(imported)
709+
if err := tester.fetcher.Notify("valid", hashes[0], 2, time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher); err != nil {
710+
t.Fatalf("failed to notify: %v", err)
711+
}
712+
select {
713+
case block := <-imported:
714+
if block.ReceivedAt.After(time.Now().Add(time.Second)) {
715+
t.Fatalf("block receive time %v is in the future", block.ReceivedAt)
716+
}
717+
case <-time.After(2 * time.Second):
718+
t.Fatal("block was not imported")
719+
}
720+
}
721+
722+
// TestWaitResponseDropsSilentPeer checks that a peer which advertises a block
723+
// and then does not serve the requested header is dropped instead of leaving
724+
// the sink waiter (and its dispatcher entry) blocked forever.
725+
func TestWaitResponseDropsSilentPeer(t *testing.T) {
726+
old := fetchResponseTimeout
727+
fetchResponseTimeout = 100 * time.Millisecond
728+
t.Cleanup(func() { fetchResponseTimeout = old })
729+
730+
tester := newIdleTester()
731+
732+
type verdict struct {
733+
res *eth.Response
734+
ok bool
735+
}
736+
verdictCh := make(chan verdict, 1)
737+
go func() {
738+
res, ok := tester.fetcher.waitResponse("silent", &eth.Request{}, make(chan *eth.Response))
739+
verdictCh <- verdict{res, ok}
740+
}()
741+
var got verdict
742+
select {
743+
case got = <-verdictCh:
744+
case <-time.After(2 * time.Second):
745+
t.Fatal("waiter did not return after the response timeout")
746+
}
747+
if got.ok || got.res != nil {
748+
t.Fatalf("silent peer: have (%v, %v), want (nil, false)", got.res, got.ok)
749+
}
750+
tester.lock.RLock()
751+
dropped := tester.drops["silent"]
752+
tester.lock.RUnlock()
753+
if !dropped {
754+
t.Fatal("silent peer was not dropped")
755+
}
756+
}
757+
758+
// TestWaitResponseStopsOnQuit checks that shutting the fetcher down releases a
759+
// sink waiter through quit, not through the timeout path that drops the peer.
760+
func TestWaitResponseStopsOnQuit(t *testing.T) {
761+
old := fetchResponseTimeout
762+
fetchResponseTimeout = 5 * time.Second
763+
t.Cleanup(func() { fetchResponseTimeout = old })
764+
765+
tester := newTester()
766+
tester.fetcher.Stop()
767+
768+
done := make(chan struct{})
769+
go func() {
770+
tester.fetcher.waitResponse("peer", &eth.Request{}, make(chan *eth.Response))
771+
close(done)
772+
}()
773+
select {
774+
case <-done:
775+
case <-time.After(time.Second):
776+
t.Fatal("Stop did not release the sink waiter")
777+
}
778+
tester.lock.RLock()
779+
dropped := tester.drops["peer"]
780+
tester.lock.RUnlock()
781+
if dropped {
782+
t.Fatal("Stop released the waiter through the timeout path")
783+
}
784+
}
785+
682786
// Tests that if blocks are announced by multiple peers (or even the same buggy
683787
// peer), they will only get downloaded at most once.
684788
func TestConcurrentAnnouncements62(t *testing.T) { testConcurrentAnnouncements(t, 62) }

0 commit comments

Comments
 (0)