Skip to content

Commit ca376ea

Browse files
zsfelfoldifjl
authored andcommitted
les, light: LES/2 protocol version (#14970)
This PR implements the new LES protocol version extensions: * new and more efficient Merkle proofs reply format (when replying to a multiple Merkle proofs request, we just send a single set of trie nodes containing all necessary nodes) * BBT (BloomBitsTrie) works similarly to the existing CHT and contains the bloombits search data to speed up log searches * GetTxStatusMsg returns the inclusion position or the pending/queued/unknown state of a transaction referenced by hash * an optional signature of new block data (number/hash/td) can be included in AnnounceMsg to provide an option for "very light clients" (mobile/embedded devices) to skip expensive Ethash check and accept multiple signatures of somewhat trusted servers (still a lot better than trusting a single server completely and retrieving everything through RPC). The new client mode is not implemented in this PR, just the protocol extension.
1 parent 6d6a5a9 commit ca376ea

34 files changed

Lines changed: 2049 additions & 481 deletions

‎core/bloombits/matcher.go‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package bloombits
1818

1919
import (
2020
"bytes"
21+
"context"
2122
"errors"
2223
"math"
2324
"sort"
@@ -60,6 +61,8 @@ type Retrieval struct {
6061
Bit uint
6162
Sections []uint64
6263
Bitsets [][]byte
64+
Error error
65+
Context context.Context
6366
}
6467

6568
// Matcher is a pipelined system of schedulers and logic matchers which perform
@@ -137,7 +140,7 @@ func (m *Matcher) addScheduler(idx uint) {
137140
// Start starts the matching process and returns a stream of bloom matches in
138141
// a given range of blocks. If there are no more matches in the range, the result
139142
// channel is closed.
140-
func (m *Matcher) Start(begin, end uint64, results chan uint64) (*MatcherSession, error) {
143+
func (m *Matcher) Start(ctx context.Context, begin, end uint64, results chan uint64) (*MatcherSession, error) {
141144
// Make sure we're not creating concurrent sessions
142145
if atomic.SwapUint32(&m.running, 1) == 1 {
143146
return nil, errors.New("matcher already running")
@@ -149,6 +152,7 @@ func (m *Matcher) Start(begin, end uint64, results chan uint64) (*MatcherSession
149152
matcher: m,
150153
quit: make(chan struct{}),
151154
kill: make(chan struct{}),
155+
ctx: ctx,
152156
}
153157
for _, scheduler := range m.schedulers {
154158
scheduler.reset()
@@ -502,15 +506,28 @@ func (m *Matcher) distributor(dist chan *request, session *MatcherSession) {
502506
type MatcherSession struct {
503507
matcher *Matcher
504508

505-
quit chan struct{} // Quit channel to request pipeline termination
506-
kill chan struct{} // Term channel to signal non-graceful forced shutdown
507-
pend sync.WaitGroup
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
508516
}
509517

510518
// Close stops the matching process and waits for all subprocesses to terminate
511519
// before returning. The timeout may be used for graceful shutdown, allowing the
512520
// currently running retrievals to complete before this time.
513-
func (s *MatcherSession) Close(timeout time.Duration) {
521+
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+
514531
// Bail out if the matcher is not running
515532
select {
516533
case <-s.quit:
@@ -519,10 +536,26 @@ func (s *MatcherSession) Close(timeout time.Duration) {
519536
}
520537
// Signal termination and wait for all goroutines to tear down
521538
close(s.quit)
522-
time.AfterFunc(timeout, func() { close(s.kill) })
539+
time.AfterFunc(time.Second, func() { close(s.kill) })
523540
s.pend.Wait()
524541
}
525542

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
552+
func (s *MatcherSession) Error() error {
553+
s.lock.Lock()
554+
defer s.lock.Unlock()
555+
556+
return s.err
557+
}
558+
526559
// AllocateRetrieval assigns a bloom bit index to a client process that can either
527560
// immediately reuest and fetch the section contents assigned to this bit or wait
528561
// a little while for more sections to be requested.
@@ -618,9 +651,13 @@ func (s *MatcherSession) Multiplex(batch int, wait time.Duration, mux chan chan
618651

619652
case mux <- request:
620653
// Retrieval accepted, something must arrive before we're aborting
621-
request <- &Retrieval{Bit: bit, Sections: sections}
654+
request <- &Retrieval{Bit: bit, Sections: sections, Context: s.ctx}
622655

623656
result := <-request
657+
if result.Error != nil {
658+
s.setError(result.Error)
659+
}
660+
624661
s.DeliverSections(result.Bit, result.Sections, result.Bitsets)
625662
}
626663
}

‎core/bloombits/matcher_test.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package bloombits
1818

1919
import (
20+
"context"
2021
"math/rand"
2122
"sync/atomic"
2223
"testing"
@@ -144,7 +145,7 @@ func testMatcher(t *testing.T, filter [][]bloomIndexes, blocks uint64, intermitt
144145
quit := make(chan struct{})
145146
matches := make(chan uint64, 16)
146147

147-
session, err := matcher.Start(0, blocks-1, matches)
148+
session, err := matcher.Start(context.Background(), 0, blocks-1, matches)
148149
if err != nil {
149150
t.Fatalf("failed to stat matcher session: %v", err)
150151
}
@@ -163,13 +164,13 @@ func testMatcher(t *testing.T, filter [][]bloomIndexes, blocks uint64, intermitt
163164
}
164165
// If we're testing intermittent mode, abort and restart the pipeline
165166
if intermittent {
166-
session.Close(time.Second)
167+
session.Close()
167168
close(quit)
168169

169170
quit = make(chan struct{})
170171
matches = make(chan uint64, 16)
171172

172-
session, err = matcher.Start(i+1, blocks-1, matches)
173+
session, err = matcher.Start(context.Background(), i+1, blocks-1, matches)
173174
if err != nil {
174175
t.Fatalf("failed to stat matcher session: %v", err)
175176
}
@@ -183,7 +184,7 @@ func testMatcher(t *testing.T, filter [][]bloomIndexes, blocks uint64, intermitt
183184
t.Errorf("filter = %v blocks = %v intermittent = %v: expected closed channel, got #%v", filter, blocks, intermittent, match)
184185
}
185186
// Clean up the session and ensure we match the expected retrieval count
186-
session.Close(time.Second)
187+
session.Close()
187188
close(quit)
188189

189190
if retrievals != 0 && requested != retrievals {

‎core/chain_indexer.go‎

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,14 @@ 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)
39+
Reset(section uint64, lastSectionHead 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.
45+
// Commit finalizes the section metadata and stores it into the database. This
46+
// interface will usually be a batch writer.
4647
Commit() error
4748
}
4849

@@ -100,11 +101,34 @@ func NewChainIndexer(chainDb, indexDb ethdb.Database, backend ChainIndexerBacken
100101
return c
101102
}
102103

104+
// AddKnownSectionHead marks a new section head as known/processed if it is newer
105+
// than the already known best section head
106+
func (c *ChainIndexer) AddKnownSectionHead(section uint64, shead common.Hash) {
107+
c.lock.Lock()
108+
defer c.lock.Unlock()
109+
110+
if section < c.storedSections {
111+
return
112+
}
113+
c.setSectionHead(section, shead)
114+
c.setValidSections(section + 1)
115+
}
116+
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+
103123
// Start creates a goroutine to feed chain head events into the indexer for
104124
// cascading background processing. Children do not need to be started, they
105125
// are notified about new events by their parents.
106-
func (c *ChainIndexer) Start(currentHeader *types.Header, chainEventer func(ch chan<- ChainEvent) event.Subscription) {
107-
go c.eventLoop(currentHeader, chainEventer)
126+
func (c *ChainIndexer) Start(chain IndexerChain) {
127+
ch := make(chan ChainEvent, 10)
128+
sub := chain.SubscribeChainEvent(ch)
129+
currentHeader := chain.CurrentHeader()
130+
131+
go c.eventLoop(currentHeader, ch, sub)
108132
}
109133

110134
// Close tears down all goroutines belonging to the indexer and returns any error
@@ -125,12 +149,14 @@ func (c *ChainIndexer) Close() error {
125149
errs = append(errs, err)
126150
}
127151
}
152+
128153
// Close all children
129154
for _, child := range c.children {
130155
if err := child.Close(); err != nil {
131156
errs = append(errs, err)
132157
}
133158
}
159+
134160
// Return any failures
135161
switch {
136162
case len(errs) == 0:
@@ -147,12 +173,10 @@ func (c *ChainIndexer) Close() error {
147173
// eventLoop is a secondary - optional - event loop of the indexer which is only
148174
// started for the outermost indexer to push chain head events into a processing
149175
// queue.
150-
func (c *ChainIndexer) eventLoop(currentHeader *types.Header, chainEventer func(ch chan<- ChainEvent) event.Subscription) {
176+
func (c *ChainIndexer) eventLoop(currentHeader *types.Header, ch chan ChainEvent, sub event.Subscription) {
151177
// Mark the chain indexer as active, requiring an additional teardown
152178
atomic.StoreUint32(&c.active, 1)
153179

154-
events := make(chan ChainEvent, 10)
155-
sub := chainEventer(events)
156180
defer sub.Unsubscribe()
157181

158182
// Fire the initial new head event to start any outstanding processing
@@ -169,7 +193,7 @@ func (c *ChainIndexer) eventLoop(currentHeader *types.Header, chainEventer func(
169193
errc <- nil
170194
return
171195

172-
case ev, ok := <-events:
196+
case ev, ok := <-ch:
173197
// Received a new event, ensure it's not nil (closing) and update
174198
if !ok {
175199
errc := <-c.quit
@@ -178,7 +202,9 @@ func (c *ChainIndexer) eventLoop(currentHeader *types.Header, chainEventer func(
178202
}
179203
header := ev.Block.Header()
180204
if header.ParentHash != prevHash {
181-
c.newHead(FindCommonAncestor(c.chainDb, prevHeader, header).Number.Uint64(), true)
205+
if h := FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
206+
c.newHead(h.Number.Uint64(), true)
207+
}
182208
}
183209
c.newHead(header.Number.Uint64(), false)
184210

@@ -233,9 +259,10 @@ func (c *ChainIndexer) newHead(head uint64, reorg bool) {
233259
// down into the processing backend.
234260
func (c *ChainIndexer) updateLoop() {
235261
var (
236-
updating bool
237-
updated time.Time
262+
updated time.Time
263+
updateMsg bool
238264
)
265+
239266
for {
240267
select {
241268
case errc := <-c.quit:
@@ -250,7 +277,7 @@ func (c *ChainIndexer) updateLoop() {
250277
// Periodically print an upgrade log message to the user
251278
if time.Since(updated) > 8*time.Second {
252279
if c.knownSections > c.storedSections+1 {
253-
updating = true
280+
updateMsg = true
254281
c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
255282
}
256283
updated = time.Now()
@@ -259,7 +286,7 @@ func (c *ChainIndexer) updateLoop() {
259286
section := c.storedSections
260287
var oldHead common.Hash
261288
if section > 0 {
262-
oldHead = c.sectionHead(section - 1)
289+
oldHead = c.SectionHead(section - 1)
263290
}
264291
// Process the newly defined section in the background
265292
c.lock.Unlock()
@@ -270,11 +297,11 @@ func (c *ChainIndexer) updateLoop() {
270297
c.lock.Lock()
271298

272299
// If processing succeeded and no reorgs occcurred, mark the section completed
273-
if err == nil && oldHead == c.sectionHead(section-1) {
300+
if err == nil && oldHead == c.SectionHead(section-1) {
274301
c.setSectionHead(section, newHead)
275302
c.setValidSections(section + 1)
276-
if c.storedSections == c.knownSections && updating {
277-
updating = false
303+
if c.storedSections == c.knownSections && updateMsg {
304+
updateMsg = false
278305
c.log.Info("Finished upgrading chain index")
279306
}
280307

@@ -311,7 +338,11 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
311338
c.log.Trace("Processing new chain section", "section", section)
312339

313340
// Reset and partial processing
314-
c.backend.Reset(section)
341+
342+
if err := c.backend.Reset(section, lastHead); err != nil {
343+
c.setValidSections(0)
344+
return common.Hash{}, err
345+
}
315346

316347
for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
317348
hash := GetCanonicalHash(c.chainDb, number)
@@ -341,7 +372,7 @@ func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
341372
c.lock.Lock()
342373
defer c.lock.Unlock()
343374

344-
return c.storedSections, c.storedSections*c.sectionSize - 1, c.sectionHead(c.storedSections - 1)
375+
return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
345376
}
346377

347378
// AddChildIndexer adds a child ChainIndexer that can use the output of this one
@@ -383,7 +414,7 @@ func (c *ChainIndexer) setValidSections(sections uint64) {
383414

384415
// sectionHead retrieves the last block hash of a processed section from the
385416
// index database.
386-
func (c *ChainIndexer) sectionHead(section uint64) common.Hash {
417+
func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
387418
var data [8]byte
388419
binary.BigEndian.PutUint64(data[:], section)
389420

‎core/chain_indexer_test.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"testing"
2424
"time"
2525

26+
"github.com/ethereum/go-ethereum/common"
2627
"github.com/ethereum/go-ethereum/core/types"
2728
"github.com/ethereum/go-ethereum/ethdb"
2829
)
@@ -208,9 +209,10 @@ func (b *testChainIndexBackend) reorg(headNum uint64) uint64 {
208209
return b.stored * b.indexer.sectionSize
209210
}
210211

211-
func (b *testChainIndexBackend) Reset(section uint64) {
212+
func (b *testChainIndexBackend) Reset(section uint64, lastSectionHead common.Hash) error {
212213
b.section = section
213214
b.headerCnt = 0
215+
return nil
214216
}
215217

216218
func (b *testChainIndexBackend) Process(header *types.Header) {

0 commit comments

Comments
 (0)