Skip to content

Commit 0095531

Browse files
authored
core, eth, les: fix messy code (#15367)
* core, eth, les: fix messy code * les: fixed tx status test and rlp encoding * core: add a workaround for light sync
1 parent ca376ea commit 0095531

11 files changed

Lines changed: 175 additions & 203 deletions

File tree

‎core/bloombits/matcher.go‎

Lines changed: 24 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,16 @@ type partialMatches struct {
5757
// Retrieval represents a request for retrieval task assignments for a given
5858
// bit with the given number of fetch elements, or a response for such a request.
5959
// It can also have the actual results set to be used as a delivery data struct.
60+
//
61+
// The contest and error fields are used by the light client to terminate matching
62+
// early if an error is enountered on some path of the pipeline.
6063
type Retrieval struct {
6164
Bit uint
6265
Sections []uint64
6366
Bitsets [][]byte
64-
Error error
65-
Context context.Context
67+
68+
Context context.Context
69+
Error error
6670
}
6771

6872
// Matcher is a pipelined system of schedulers and logic matchers which perform
@@ -506,54 +510,31 @@ func (m *Matcher) distributor(dist chan *request, session *MatcherSession) {
506510
type MatcherSession struct {
507511
matcher *Matcher
508512

509-
quit chan struct{} // Quit channel to request pipeline termination
510-
kill chan struct{} // Term channel to signal non-graceful forced shutdown
511-
ctx context.Context
512-
err error
513-
stopping bool
514-
lock sync.Mutex
515-
pend sync.WaitGroup
513+
closer sync.Once // Sync object to ensure we only ever close once
514+
quit chan struct{} // Quit channel to request pipeline termination
515+
kill chan struct{} // Term channel to signal non-graceful forced shutdown
516+
517+
ctx context.Context // Context used by the light client to abort filtering
518+
err atomic.Value // Global error to track retrieval failures deep in the chain
519+
520+
pend sync.WaitGroup
516521
}
517522

518523
// Close stops the matching process and waits for all subprocesses to terminate
519524
// before returning. The timeout may be used for graceful shutdown, allowing the
520525
// currently running retrievals to complete before this time.
521526
func (s *MatcherSession) Close() {
522-
s.lock.Lock()
523-
stopping := s.stopping
524-
s.stopping = true
525-
s.lock.Unlock()
526-
// ensure that we only close the session once
527-
if stopping {
528-
return
529-
}
530-
531-
// Bail out if the matcher is not running
532-
select {
533-
case <-s.quit:
534-
return
535-
default:
536-
}
537-
// Signal termination and wait for all goroutines to tear down
538-
close(s.quit)
539-
time.AfterFunc(time.Second, func() { close(s.kill) })
540-
s.pend.Wait()
527+
s.closer.Do(func() {
528+
// Signal termination and wait for all goroutines to tear down
529+
close(s.quit)
530+
time.AfterFunc(time.Second, func() { close(s.kill) })
531+
s.pend.Wait()
532+
})
541533
}
542534

543-
// setError sets an error and stops the session
544-
func (s *MatcherSession) setError(err error) {
545-
s.lock.Lock()
546-
s.err = err
547-
s.lock.Unlock()
548-
s.Close()
549-
}
550-
551-
// Error returns an error if one has happened during the session
535+
// Error returns any failure encountered during the matching session.
552536
func (s *MatcherSession) Error() error {
553-
s.lock.Lock()
554-
defer s.lock.Unlock()
555-
556-
return s.err
537+
return s.err.Load().(error)
557538
}
558539

559540
// AllocateRetrieval assigns a bloom bit index to a client process that can either
@@ -655,9 +636,9 @@ func (s *MatcherSession) Multiplex(batch int, wait time.Duration, mux chan chan
655636

656637
result := <-request
657638
if result.Error != nil {
658-
s.setError(result.Error)
639+
s.err.Store(result.Error)
640+
s.Close()
659641
}
660-
661642
s.DeliverSections(result.Bit, result.Sections, result.Bitsets)
662643
}
663644
}

‎core/chain_indexer.go‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -36,17 +36,25 @@ import (
3636
type ChainIndexerBackend interface {
3737
// Reset initiates the processing of a new chain segment, potentially terminating
3838
// any partially completed operations (in case of a reorg).
39-
Reset(section uint64, lastSectionHead common.Hash) error
39+
Reset(section uint64, prevHead common.Hash) error
4040

4141
// Process crunches through the next header in the chain segment. The caller
4242
// will ensure a sequential order of headers.
4343
Process(header *types.Header)
4444

45-
// Commit finalizes the section metadata and stores it into the database. This
46-
// interface will usually be a batch writer.
45+
// Commit finalizes the section metadata and stores it into the database.
4746
Commit() error
4847
}
4948

49+
// ChainIndexerChain interface is used for connecting the indexer to a blockchain
50+
type ChainIndexerChain interface {
51+
// CurrentHeader retrieves the latest locally known header.
52+
CurrentHeader() *types.Header
53+
54+
// SubscribeChainEvent subscribes to new head header notifications.
55+
SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription
56+
}
57+
5058
// ChainIndexer does a post-processing job for equally sized sections of the
5159
// canonical chain (like BlooomBits and CHT structures). A ChainIndexer is
5260
// connected to the blockchain through the event system by starting a
@@ -114,21 +122,14 @@ func (c *ChainIndexer) AddKnownSectionHead(section uint64, shead common.Hash) {
114122
c.setValidSections(section + 1)
115123
}
116124

117-
// IndexerChain interface is used for connecting the indexer to a blockchain
118-
type IndexerChain interface {
119-
CurrentHeader() *types.Header
120-
SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription
121-
}
122-
123125
// Start creates a goroutine to feed chain head events into the indexer for
124126
// cascading background processing. Children do not need to be started, they
125127
// are notified about new events by their parents.
126-
func (c *ChainIndexer) Start(chain IndexerChain) {
127-
ch := make(chan ChainEvent, 10)
128-
sub := chain.SubscribeChainEvent(ch)
129-
currentHeader := chain.CurrentHeader()
128+
func (c *ChainIndexer) Start(chain ChainIndexerChain) {
129+
events := make(chan ChainEvent, 10)
130+
sub := chain.SubscribeChainEvent(events)
130131

131-
go c.eventLoop(currentHeader, ch, sub)
132+
go c.eventLoop(chain.CurrentHeader(), events, sub)
132133
}
133134

134135
// Close tears down all goroutines belonging to the indexer and returns any error
@@ -149,14 +150,12 @@ func (c *ChainIndexer) Close() error {
149150
errs = append(errs, err)
150151
}
151152
}
152-
153153
// Close all children
154154
for _, child := range c.children {
155155
if err := child.Close(); err != nil {
156156
errs = append(errs, err)
157157
}
158158
}
159-
160159
// Return any failures
161160
switch {
162161
case len(errs) == 0:
@@ -173,7 +172,7 @@ func (c *ChainIndexer) Close() error {
173172
// eventLoop is a secondary - optional - event loop of the indexer which is only
174173
// started for the outermost indexer to push chain head events into a processing
175174
// queue.
176-
func (c *ChainIndexer) eventLoop(currentHeader *types.Header, ch chan ChainEvent, sub event.Subscription) {
175+
func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainEvent, sub event.Subscription) {
177176
// Mark the chain indexer as active, requiring an additional teardown
178177
atomic.StoreUint32(&c.active, 1)
179178

@@ -193,7 +192,7 @@ func (c *ChainIndexer) eventLoop(currentHeader *types.Header, ch chan ChainEvent
193192
errc <- nil
194193
return
195194

196-
case ev, ok := <-ch:
195+
case ev, ok := <-events:
197196
// Received a new event, ensure it's not nil (closing) and update
198197
if !ok {
199198
errc := <-c.quit
@@ -202,6 +201,8 @@ func (c *ChainIndexer) eventLoop(currentHeader *types.Header, ch chan ChainEvent
202201
}
203202
header := ev.Block.Header()
204203
if header.ParentHash != prevHash {
204+
// Reorg to the common ancestor (might not exist in light sync mode, skip reorg then)
205+
// TODO(karalabe, zsfelfoldi): This seems a bit brittle, can we detect this case explicitly?
205206
if h := FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
206207
c.newHead(h.Number.Uint64(), true)
207208
}
@@ -259,8 +260,8 @@ func (c *ChainIndexer) newHead(head uint64, reorg bool) {
259260
// down into the processing backend.
260261
func (c *ChainIndexer) updateLoop() {
261262
var (
262-
updated time.Time
263-
updateMsg bool
263+
updating bool
264+
updated time.Time
264265
)
265266

266267
for {
@@ -277,7 +278,7 @@ func (c *ChainIndexer) updateLoop() {
277278
// Periodically print an upgrade log message to the user
278279
if time.Since(updated) > 8*time.Second {
279280
if c.knownSections > c.storedSections+1 {
280-
updateMsg = true
281+
updating = true
281282
c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
282283
}
283284
updated = time.Now()
@@ -300,8 +301,8 @@ func (c *ChainIndexer) updateLoop() {
300301
if err == nil && oldHead == c.SectionHead(section-1) {
301302
c.setSectionHead(section, newHead)
302303
c.setValidSections(section + 1)
303-
if c.storedSections == c.knownSections && updateMsg {
304-
updateMsg = false
304+
if c.storedSections == c.knownSections && updating {
305+
updating = false
305306
c.log.Info("Finished upgrading chain index")
306307
}
307308

@@ -412,7 +413,7 @@ func (c *ChainIndexer) setValidSections(sections uint64) {
412413
c.storedSections = sections // needed if new > old
413414
}
414415

415-
// sectionHead retrieves the last block hash of a processed section from the
416+
// SectionHead retrieves the last block hash of a processed section from the
416417
// index database.
417418
func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
418419
var data [8]byte

‎core/chain_indexer_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ func (b *testChainIndexBackend) reorg(headNum uint64) uint64 {
209209
return b.stored * b.indexer.sectionSize
210210
}
211211

212-
func (b *testChainIndexBackend) Reset(section uint64, lastSectionHead common.Hash) error {
212+
func (b *testChainIndexBackend) Reset(section uint64, prevHead common.Hash) error {
213213
b.section = section
214214
b.headerCnt = 0
215215
return nil

‎core/tx_list.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -384,13 +384,13 @@ func (h *priceHeap) Pop() interface{} {
384384
// txPricedList is a price-sorted heap to allow operating on transactions pool
385385
// contents in a price-incrementing way.
386386
type txPricedList struct {
387-
all *map[common.Hash]txLookupRec // Pointer to the map of all transactions
388-
items *priceHeap // Heap of prices of all the stored transactions
389-
stales int // Number of stale price points to (re-heap trigger)
387+
all *map[common.Hash]*types.Transaction // Pointer to the map of all transactions
388+
items *priceHeap // Heap of prices of all the stored transactions
389+
stales int // Number of stale price points to (re-heap trigger)
390390
}
391391

392392
// newTxPricedList creates a new price-sorted transaction heap.
393-
func newTxPricedList(all *map[common.Hash]txLookupRec) *txPricedList {
393+
func newTxPricedList(all *map[common.Hash]*types.Transaction) *txPricedList {
394394
return &txPricedList{
395395
all: all,
396396
items: new(priceHeap),
@@ -416,7 +416,7 @@ func (l *txPricedList) Removed() {
416416

417417
l.stales, l.items = 0, &reheap
418418
for _, tx := range *l.all {
419-
*l.items = append(*l.items, tx.tx)
419+
*l.items = append(*l.items, tx)
420420
}
421421
heap.Init(l.items)
422422
}

0 commit comments

Comments
 (0)