Skip to content

Commit c4307a9

Browse files
authored
eth/filters: fix potential deadlock in filter timeout loop (#22178)
This fixes #22131 and adds a test reproducing the issue.
1 parent ddadc3d commit c4307a9

4 files changed

Lines changed: 101 additions & 22 deletions

File tree

‎eth/backend.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ func (s *Ethereum) APIs() []rpc.API {
335335
}, {
336336
Namespace: "eth",
337337
Version: "1.0",
338-
Service: filters.NewPublicFilterAPI(s.APIBackend, false),
338+
Service: filters.NewPublicFilterAPI(s.APIBackend, false, 5*time.Minute),
339339
Public: true,
340340
}, {
341341
Namespace: "admin",

‎eth/filters/api.go‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,6 @@ import (
3434
"github.com/ethereum/go-ethereum/rpc"
3535
)
3636

37-
var (
38-
deadline = 5 * time.Minute // consider a filter inactive if it has not been polled for within deadline
39-
)
40-
4137
// filter is a helper struct that holds meta information over the filter type
4238
// and associated subscription in the event system.
4339
type filter struct {
@@ -59,39 +55,50 @@ type PublicFilterAPI struct {
5955
events *EventSystem
6056
filtersMu sync.Mutex
6157
filters map[rpc.ID]*filter
58+
timeout time.Duration
6259
}
6360

6461
// NewPublicFilterAPI returns a new PublicFilterAPI instance.
65-
func NewPublicFilterAPI(backend Backend, lightMode bool) *PublicFilterAPI {
62+
func NewPublicFilterAPI(backend Backend, lightMode bool, timeout time.Duration) *PublicFilterAPI {
6663
api := &PublicFilterAPI{
6764
backend: backend,
6865
chainDb: backend.ChainDb(),
6966
events: NewEventSystem(backend, lightMode),
7067
filters: make(map[rpc.ID]*filter),
68+
timeout: timeout,
7169
}
72-
go api.timeoutLoop()
70+
go api.timeoutLoop(timeout)
7371

7472
return api
7573
}
7674

7775
// timeoutLoop runs every 5 minutes and deletes filters that have not been recently used.
7876
// Tt is started when the api is created.
79-
func (api *PublicFilterAPI) timeoutLoop() {
80-
ticker := time.NewTicker(5 * time.Minute)
77+
func (api *PublicFilterAPI) timeoutLoop(timeout time.Duration) {
78+
var toUninstall []*Subscription
79+
ticker := time.NewTicker(timeout)
8180
defer ticker.Stop()
8281
for {
8382
<-ticker.C
8483
api.filtersMu.Lock()
8584
for id, f := range api.filters {
8685
select {
8786
case <-f.deadline.C:
88-
f.s.Unsubscribe()
87+
toUninstall = append(toUninstall, f.s)
8988
delete(api.filters, id)
9089
default:
9190
continue
9291
}
9392
}
9493
api.filtersMu.Unlock()
94+
95+
// Unsubscribes are processed outside the lock to avoid the following scenario:
96+
// event loop attempts broadcasting events to still active filters while
97+
// Unsubscribe is waiting for it to process the uninstall request.
98+
for _, s := range toUninstall {
99+
s.Unsubscribe()
100+
}
101+
toUninstall = nil
95102
}
96103
}
97104

@@ -109,7 +116,7 @@ func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID {
109116
)
110117

111118
api.filtersMu.Lock()
112-
api.filters[pendingTxSub.ID] = &filter{typ: PendingTransactionsSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: pendingTxSub}
119+
api.filters[pendingTxSub.ID] = &filter{typ: PendingTransactionsSubscription, deadline: time.NewTimer(api.timeout), hashes: make([]common.Hash, 0), s: pendingTxSub}
113120
api.filtersMu.Unlock()
114121

115122
go func() {
@@ -179,7 +186,7 @@ func (api *PublicFilterAPI) NewBlockFilter() rpc.ID {
179186
)
180187

181188
api.filtersMu.Lock()
182-
api.filters[headerSub.ID] = &filter{typ: BlocksSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: headerSub}
189+
api.filters[headerSub.ID] = &filter{typ: BlocksSubscription, deadline: time.NewTimer(api.timeout), hashes: make([]common.Hash, 0), s: headerSub}
183190
api.filtersMu.Unlock()
184191

185192
go func() {
@@ -296,7 +303,7 @@ func (api *PublicFilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) {
296303
}
297304

298305
api.filtersMu.Lock()
299-
api.filters[logsSub.ID] = &filter{typ: LogsSubscription, crit: crit, deadline: time.NewTimer(deadline), logs: make([]*types.Log, 0), s: logsSub}
306+
api.filters[logsSub.ID] = &filter{typ: LogsSubscription, crit: crit, deadline: time.NewTimer(api.timeout), logs: make([]*types.Log, 0), s: logsSub}
300307
api.filtersMu.Unlock()
301308

302309
go func() {
@@ -421,7 +428,7 @@ func (api *PublicFilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) {
421428
// receive timer value and reset timer
422429
<-f.deadline.C
423430
}
424-
f.deadline.Reset(deadline)
431+
f.deadline.Reset(api.timeout)
425432

426433
switch f.typ {
427434
case PendingTransactionsSubscription, BlocksSubscription:

‎eth/filters/filter_system_test.go‎

Lines changed: 79 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"math/big"
2323
"math/rand"
2424
"reflect"
25+
"runtime"
2526
"testing"
2627
"time"
2728

@@ -38,6 +39,10 @@ import (
3839
"github.com/ethereum/go-ethereum/rpc"
3940
)
4041

42+
var (
43+
deadline = 5 * time.Minute
44+
)
45+
4146
type testBackend struct {
4247
mux *event.TypeMux
4348
db ethdb.Database
@@ -163,7 +168,7 @@ func TestBlockSubscription(t *testing.T) {
163168
var (
164169
db = rawdb.NewMemoryDatabase()
165170
backend = &testBackend{db: db}
166-
api = NewPublicFilterAPI(backend, false)
171+
api = NewPublicFilterAPI(backend, false, deadline)
167172
genesis = new(core.Genesis).MustCommit(db)
168173
chain, _ = core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {})
169174
chainEvents = []core.ChainEvent{}
@@ -215,7 +220,7 @@ func TestPendingTxFilter(t *testing.T) {
215220
var (
216221
db = rawdb.NewMemoryDatabase()
217222
backend = &testBackend{db: db}
218-
api = NewPublicFilterAPI(backend, false)
223+
api = NewPublicFilterAPI(backend, false, deadline)
219224

220225
transactions = []*types.Transaction{
221226
types.NewTransaction(0, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), 0, new(big.Int), nil),
@@ -270,7 +275,7 @@ func TestLogFilterCreation(t *testing.T) {
270275
var (
271276
db = rawdb.NewMemoryDatabase()
272277
backend = &testBackend{db: db}
273-
api = NewPublicFilterAPI(backend, false)
278+
api = NewPublicFilterAPI(backend, false, deadline)
274279

275280
testCases = []struct {
276281
crit FilterCriteria
@@ -314,7 +319,7 @@ func TestInvalidLogFilterCreation(t *testing.T) {
314319
var (
315320
db = rawdb.NewMemoryDatabase()
316321
backend = &testBackend{db: db}
317-
api = NewPublicFilterAPI(backend, false)
322+
api = NewPublicFilterAPI(backend, false, deadline)
318323
)
319324

320325
// different situations where log filter creation should fail.
@@ -336,7 +341,7 @@ func TestInvalidGetLogsRequest(t *testing.T) {
336341
var (
337342
db = rawdb.NewMemoryDatabase()
338343
backend = &testBackend{db: db}
339-
api = NewPublicFilterAPI(backend, false)
344+
api = NewPublicFilterAPI(backend, false, deadline)
340345
blockHash = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111")
341346
)
342347

@@ -361,7 +366,7 @@ func TestLogFilter(t *testing.T) {
361366
var (
362367
db = rawdb.NewMemoryDatabase()
363368
backend = &testBackend{db: db}
364-
api = NewPublicFilterAPI(backend, false)
369+
api = NewPublicFilterAPI(backend, false, deadline)
365370

366371
firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111")
367372
secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222")
@@ -475,7 +480,7 @@ func TestPendingLogsSubscription(t *testing.T) {
475480
var (
476481
db = rawdb.NewMemoryDatabase()
477482
backend = &testBackend{db: db}
478-
api = NewPublicFilterAPI(backend, false)
483+
api = NewPublicFilterAPI(backend, false, deadline)
479484

480485
firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111")
481486
secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222")
@@ -601,6 +606,73 @@ func TestPendingLogsSubscription(t *testing.T) {
601606
}
602607
}
603608

609+
// TestPendingTxFilterDeadlock tests if the event loop hangs when pending
610+
// txes arrive at the same time that one of multiple filters is timing out.
611+
// Please refer to #22131 for more details.
612+
func TestPendingTxFilterDeadlock(t *testing.T) {
613+
t.Parallel()
614+
timeout := 100 * time.Millisecond
615+
616+
var (
617+
db = rawdb.NewMemoryDatabase()
618+
backend = &testBackend{db: db}
619+
api = NewPublicFilterAPI(backend, false, timeout)
620+
done = make(chan struct{})
621+
)
622+
623+
go func() {
624+
// Bombard feed with txes until signal was received to stop
625+
i := uint64(0)
626+
for {
627+
select {
628+
case <-done:
629+
return
630+
default:
631+
}
632+
633+
tx := types.NewTransaction(i, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), 0, new(big.Int), nil)
634+
backend.txFeed.Send(core.NewTxsEvent{Txs: []*types.Transaction{tx}})
635+
i++
636+
}
637+
}()
638+
639+
// Create a bunch of filters that will
640+
// timeout either in 100ms or 200ms
641+
fids := make([]rpc.ID, 20)
642+
for i := 0; i < len(fids); i++ {
643+
fid := api.NewPendingTransactionFilter()
644+
fids[i] = fid
645+
// Wait for at least one tx to arrive in filter
646+
for {
647+
hashes, err := api.GetFilterChanges(fid)
648+
if err != nil {
649+
t.Fatalf("Filter should exist: %v\n", err)
650+
}
651+
if len(hashes.([]common.Hash)) > 0 {
652+
break
653+
}
654+
runtime.Gosched()
655+
}
656+
}
657+
658+
// Wait until filters have timed out
659+
time.Sleep(3 * timeout)
660+
661+
// If tx loop doesn't consume `done` after a second
662+
// it's hanging.
663+
select {
664+
case done <- struct{}{}:
665+
// Check that all filters have been uninstalled
666+
for _, fid := range fids {
667+
if _, err := api.GetFilterChanges(fid); err == nil {
668+
t.Errorf("Filter %s should have been uninstalled\n", fid)
669+
}
670+
}
671+
case <-time.After(1 * time.Second):
672+
t.Error("Tx sending loop hangs")
673+
}
674+
}
675+
604676
func flattenLogs(pl [][]*types.Log) []*types.Log {
605677
var logs []*types.Log
606678
for _, l := range pl {

‎les/client.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ func (s *LightEthereum) APIs() []rpc.API {
252252
}, {
253253
Namespace: "eth",
254254
Version: "1.0",
255-
Service: filters.NewPublicFilterAPI(s.ApiBackend, true),
255+
Service: filters.NewPublicFilterAPI(s.ApiBackend, true, 5*time.Minute),
256256
Public: true,
257257
}, {
258258
Namespace: "net",

0 commit comments

Comments
 (0)