Skip to content

Commit cefe5c8

Browse files
committed
Merge pull request bnb-chain#1898 from karalabe/eventmux-post-race
core, eth, event, miner, xeth: fix event post / subscription race
2 parents 2f1f2e4 + 402fd6e commit cefe5c8

11 files changed

Lines changed: 123 additions & 94 deletions

File tree

‎core/blockchain.go‎

Lines changed: 27 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -483,13 +483,6 @@ func (bc *BlockChain) Stop() {
483483
glog.V(logger.Info).Infoln("Chain manager stopped")
484484
}
485485

486-
type queueEvent struct {
487-
queue []interface{}
488-
canonicalCount int
489-
sideCount int
490-
splitCount int
491-
}
492-
493486
func (self *BlockChain) procFutureBlocks() {
494487
blocks := make([]*types.Block, self.futureBlocks.Len())
495488
for i, hash := range self.futureBlocks.Keys() {
@@ -573,10 +566,9 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
573566
// faster than direct delivery and requires much less mutex
574567
// acquiring.
575568
var (
576-
queue = make([]interface{}, len(chain))
577-
queueEvent = queueEvent{queue: queue}
578-
stats struct{ queued, processed, ignored int }
579-
tstart = time.Now()
569+
stats struct{ queued, processed, ignored int }
570+
events = make([]interface{}, 0, len(chain))
571+
tstart = time.Now()
580572

581573
nonceChecked = make([]bool, len(chain))
582574
)
@@ -659,22 +651,21 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
659651
if glog.V(logger.Debug) {
660652
glog.Infof("[%v] inserted block #%d (%d TXs %v G %d UNCs) (%x...). Took %v\n", time.Now().UnixNano(), block.Number(), len(block.Transactions()), block.GasUsed(), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
661653
}
662-
queue[i] = ChainEvent{block, block.Hash(), logs}
663-
queueEvent.canonicalCount++
654+
events = append(events, ChainEvent{block, block.Hash(), logs})
664655

665656
// This puts transactions in a extra db for rpc
666657
PutTransactions(self.chainDb, block, block.Transactions())
667658
// store the receipts
668659
PutReceipts(self.chainDb, receipts)
660+
669661
case SideStatTy:
670662
if glog.V(logger.Detail) {
671663
glog.Infof("inserted forked block #%d (TD=%v) (%d TXs %d UNCs) (%x...). Took %v\n", block.Number(), block.Difficulty(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
672664
}
673-
queue[i] = ChainSideEvent{block, logs}
674-
queueEvent.sideCount++
665+
events = append(events, ChainSideEvent{block, logs})
666+
675667
case SplitStatTy:
676-
queue[i] = ChainSplitEvent{block, logs}
677-
queueEvent.splitCount++
668+
events = append(events, ChainSplitEvent{block, logs})
678669
}
679670
stats.processed++
680671
}
@@ -684,8 +675,7 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
684675
start, end := chain[0], chain[len(chain)-1]
685676
glog.Infof("imported %d block(s) (%d queued %d ignored) including %d txs in %v. #%v [%x / %x]\n", stats.processed, stats.queued, stats.ignored, txcount, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
686677
}
687-
688-
go self.eventMux.Post(queueEvent)
678+
go self.postChainEvents(events)
689679

690680
return 0, nil
691681
}
@@ -774,32 +764,31 @@ func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
774764
return nil
775765
}
776766

767+
// postChainEvents iterates over the events generated by a chain insertion and
768+
// posts them into the event mux.
769+
func (self *BlockChain) postChainEvents(events []interface{}) {
770+
for _, event := range events {
771+
if event, ok := event.(ChainEvent); ok {
772+
// We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
773+
// and in most cases isn't even necessary.
774+
if self.currentBlock.Hash() == event.Hash {
775+
self.currentGasLimit = CalcGasLimit(event.Block)
776+
self.eventMux.Post(ChainHeadEvent{event.Block})
777+
}
778+
}
779+
// Fire the insertion events individually too
780+
self.eventMux.Post(event)
781+
}
782+
}
783+
777784
func (self *BlockChain) update() {
778-
events := self.eventMux.Subscribe(queueEvent{})
779785
futureTimer := time.Tick(5 * time.Second)
780-
out:
781786
for {
782787
select {
783-
case ev := <-events.Chan():
784-
switch ev := ev.(type) {
785-
case queueEvent:
786-
for _, event := range ev.queue {
787-
switch event := event.(type) {
788-
case ChainEvent:
789-
// We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
790-
// and in most cases isn't even necessary.
791-
if self.currentBlock.Hash() == event.Hash {
792-
self.currentGasLimit = CalcGasLimit(event.Block)
793-
self.eventMux.Post(ChainHeadEvent{event.Block})
794-
}
795-
}
796-
self.eventMux.Post(event)
797-
}
798-
}
799788
case <-futureTimer:
800789
self.procFutureBlocks()
801790
case <-self.quit:
802-
break out
791+
return
803792
}
804793
}
805794
}

‎core/transaction_pool.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func (pool *TxPool) eventLoop() {
9393
// we need to know the new state. The new state will help us determine
9494
// the nonces in the managed state
9595
for ev := range pool.events.Chan() {
96-
switch ev := ev.(type) {
96+
switch ev := ev.Data.(type) {
9797
case ChainHeadEvent:
9898
pool.mu.Lock()
9999
pool.resetState()

‎eth/filters/filter_system.go‎

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ package filters
2020

2121
import (
2222
"sync"
23+
"time"
2324

2425
"github.com/ethereum/go-ethereum/core"
2526
"github.com/ethereum/go-ethereum/core/vm"
@@ -35,6 +36,7 @@ type FilterSystem struct {
3536
filterMu sync.RWMutex
3637
filterId int
3738
filters map[int]*Filter
39+
created map[int]time.Time
3840

3941
quit chan struct{}
4042
}
@@ -44,6 +46,7 @@ func NewFilterSystem(mux *event.TypeMux) *FilterSystem {
4446
fs := &FilterSystem{
4547
eventMux: mux,
4648
filters: make(map[int]*Filter),
49+
created: make(map[int]time.Time),
4750
}
4851
go fs.filterLoop()
4952
return fs
@@ -60,6 +63,7 @@ func (fs *FilterSystem) Add(filter *Filter) (id int) {
6063
defer fs.filterMu.Unlock()
6164
id = fs.filterId
6265
fs.filters[id] = filter
66+
fs.created[id] = time.Now()
6367
fs.filterId++
6468

6569
return id
@@ -69,58 +73,66 @@ func (fs *FilterSystem) Add(filter *Filter) (id int) {
6973
func (fs *FilterSystem) Remove(id int) {
7074
fs.filterMu.Lock()
7175
defer fs.filterMu.Unlock()
72-
if _, ok := fs.filters[id]; ok {
73-
delete(fs.filters, id)
74-
}
76+
77+
delete(fs.filters, id)
78+
delete(fs.created, id)
7579
}
7680

7781
// Get retrieves a filter installed using Add The filter may not be modified.
7882
func (fs *FilterSystem) Get(id int) *Filter {
7983
fs.filterMu.RLock()
8084
defer fs.filterMu.RUnlock()
85+
8186
return fs.filters[id]
8287
}
8388

8489
// filterLoop waits for specific events from ethereum and fires their handlers
8590
// when the filter matches the requirements.
8691
func (fs *FilterSystem) filterLoop() {
8792
// Subscribe to events
88-
events := fs.eventMux.Subscribe(
93+
eventCh := fs.eventMux.Subscribe(
8994
//core.PendingBlockEvent{},
9095
core.ChainEvent{},
9196
core.TxPreEvent{},
92-
vm.Logs(nil))
97+
vm.Logs(nil),
98+
).Chan()
9399

94100
out:
95101
for {
96102
select {
97103
case <-fs.quit:
98104
break out
99-
case event := <-events.Chan():
100-
switch event := event.(type) {
105+
case event, ok := <-eventCh:
106+
if !ok {
107+
// Event subscription closed, set the channel to nil to stop spinning
108+
eventCh = nil
109+
continue
110+
}
111+
// A real event arrived, notify the registered filters
112+
switch ev := event.Data.(type) {
101113
case core.ChainEvent:
102114
fs.filterMu.RLock()
103-
for _, filter := range fs.filters {
104-
if filter.BlockCallback != nil {
105-
filter.BlockCallback(event.Block, event.Logs)
115+
for id, filter := range fs.filters {
116+
if filter.BlockCallback != nil && fs.created[id].Before(event.Time) {
117+
filter.BlockCallback(ev.Block, ev.Logs)
106118
}
107119
}
108120
fs.filterMu.RUnlock()
109121

110122
case core.TxPreEvent:
111123
fs.filterMu.RLock()
112-
for _, filter := range fs.filters {
113-
if filter.TransactionCallback != nil {
114-
filter.TransactionCallback(event.Tx)
124+
for id, filter := range fs.filters {
125+
if filter.TransactionCallback != nil && fs.created[id].Before(event.Time) {
126+
filter.TransactionCallback(ev.Tx)
115127
}
116128
}
117129
fs.filterMu.RUnlock()
118130

119131
case vm.Logs:
120132
fs.filterMu.RLock()
121-
for _, filter := range fs.filters {
122-
if filter.LogsCallback != nil {
123-
msgs := filter.FilterLogs(event)
133+
for id, filter := range fs.filters {
134+
if filter.LogsCallback != nil && fs.created[id].Before(event.Time) {
135+
msgs := filter.FilterLogs(ev)
124136
if len(msgs) > 0 {
125137
filter.LogsCallback(msgs)
126138
}

‎eth/gasprice.go‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,19 +84,16 @@ func (self *GasPriceOracle) processPastBlocks() {
8484
}
8585

8686
func (self *GasPriceOracle) listenLoop() {
87-
for {
88-
ev, isopen := <-self.events.Chan()
89-
if !isopen {
90-
break
91-
}
92-
switch ev := ev.(type) {
87+
defer self.events.Unsubscribe()
88+
89+
for event := range self.events.Chan() {
90+
switch event := event.Data.(type) {
9391
case core.ChainEvent:
94-
self.processBlock(ev.Block)
92+
self.processBlock(event.Block)
9593
case core.ChainSplitEvent:
96-
self.processBlock(ev.Block)
94+
self.processBlock(event.Block)
9795
}
9896
}
99-
self.events.Unsubscribe()
10097
}
10198

10299
func (self *GasPriceOracle) processBlock(block *types.Block) {

‎eth/handler.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction)
687687
func (self *ProtocolManager) minedBroadcastLoop() {
688688
// automatically stops if unsubscribe
689689
for obj := range self.minedBlockSub.Chan() {
690-
switch ev := obj.(type) {
690+
switch ev := obj.Data.(type) {
691691
case core.NewMinedBlockEvent:
692692
self.BroadcastBlock(ev.Block, true) // First propagate block to peers
693693
self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
@@ -698,7 +698,7 @@ func (self *ProtocolManager) minedBroadcastLoop() {
698698
func (self *ProtocolManager) txBroadcastLoop() {
699699
// automatically stops if unsubscribe
700700
for obj := range self.txSub.Chan() {
701-
event := obj.(core.TxPreEvent)
701+
event := obj.Data.(core.TxPreEvent)
702702
self.BroadcastTx(event.Tx.Hash(), event.Tx)
703703
}
704704
}

‎event/event.go‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,21 @@ import (
2222
"fmt"
2323
"reflect"
2424
"sync"
25+
"time"
2526
)
2627

28+
// Event is a time-tagged notification pushed to subscribers.
29+
type Event struct {
30+
Time time.Time
31+
Data interface{}
32+
}
33+
2734
// Subscription is implemented by event subscriptions.
2835
type Subscription interface {
2936
// Chan returns a channel that carries events.
3037
// Implementations should return the same channel
3138
// for any subsequent calls to Chan.
32-
Chan() <-chan interface{}
39+
Chan() <-chan *Event
3340

3441
// Unsubscribe stops delivery of events to a subscription.
3542
// The event channel is closed.
@@ -82,6 +89,10 @@ func (mux *TypeMux) Subscribe(types ...interface{}) Subscription {
8289
// Post sends an event to all receivers registered for the given type.
8390
// It returns ErrMuxClosed if the mux has been stopped.
8491
func (mux *TypeMux) Post(ev interface{}) error {
92+
event := &Event{
93+
Time: time.Now(),
94+
Data: ev,
95+
}
8596
rtyp := reflect.TypeOf(ev)
8697
mux.mutex.RLock()
8798
if mux.stopped {
@@ -91,7 +102,7 @@ func (mux *TypeMux) Post(ev interface{}) error {
91102
subs := mux.subm[rtyp]
92103
mux.mutex.RUnlock()
93104
for _, sub := range subs {
94-
sub.deliver(ev)
105+
sub.deliver(event)
95106
}
96107
return nil
97108
}
@@ -143,6 +154,7 @@ func posdelete(slice []*muxsub, pos int) []*muxsub {
143154

144155
type muxsub struct {
145156
mux *TypeMux
157+
created time.Time
146158
closeMu sync.Mutex
147159
closing chan struct{}
148160
closed bool
@@ -151,21 +163,22 @@ type muxsub struct {
151163
// postC can be set to nil without affecting the return value of
152164
// Chan.
153165
postMu sync.RWMutex
154-
readC <-chan interface{}
155-
postC chan<- interface{}
166+
readC <-chan *Event
167+
postC chan<- *Event
156168
}
157169

158170
func newsub(mux *TypeMux) *muxsub {
159-
c := make(chan interface{})
171+
c := make(chan *Event)
160172
return &muxsub{
161173
mux: mux,
174+
created: time.Now(),
162175
readC: c,
163176
postC: c,
164177
closing: make(chan struct{}),
165178
}
166179
}
167180

168-
func (s *muxsub) Chan() <-chan interface{} {
181+
func (s *muxsub) Chan() <-chan *Event {
169182
return s.readC
170183
}
171184

@@ -189,11 +202,17 @@ func (s *muxsub) closewait() {
189202
s.postMu.Unlock()
190203
}
191204

192-
func (s *muxsub) deliver(ev interface{}) {
205+
func (s *muxsub) deliver(event *Event) {
206+
// Short circuit delivery if stale event
207+
if s.created.After(event.Time) {
208+
return
209+
}
210+
// Otherwise deliver the event
193211
s.postMu.RLock()
212+
defer s.postMu.RUnlock()
213+
194214
select {
195-
case s.postC <- ev:
215+
case s.postC <- event:
196216
case <-s.closing:
197217
}
198-
s.postMu.RUnlock()
199218
}

‎event/event_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func TestSub(t *testing.T) {
3737
}()
3838
ev := <-sub.Chan()
3939

40-
if ev.(testEvent) != testEvent(5) {
40+
if ev.Data.(testEvent) != testEvent(5) {
4141
t.Errorf("Got %v (%T), expected event %v (%T)",
4242
ev, ev, testEvent(5), testEvent(5))
4343
}

0 commit comments

Comments
 (0)