Skip to content

Commit 2cdf6ee

Browse files
zsfelfoldifjl
authored andcommitted
light: CHT and bloom trie indexers working in light mode (#16534)
This PR enables the indexers to work in light client mode by downloading a part of these tries (the Merkle proofs of the last values of the last known section) in order to be able to add new values and recalculate subsequent hashes. It also adds CHT data to NodeInfo.
1 parent e8752f4 commit 2cdf6ee

16 files changed

Lines changed: 251 additions & 112 deletions

‎core/chain_indexer.go‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package core
1818

1919
import (
20+
"context"
2021
"encoding/binary"
2122
"fmt"
2223
"sync"
@@ -37,11 +38,11 @@ import (
3738
type ChainIndexerBackend interface {
3839
// Reset initiates the processing of a new chain segment, potentially terminating
3940
// any partially completed operations (in case of a reorg).
40-
Reset(section uint64, prevHead common.Hash) error
41+
Reset(ctx context.Context, section uint64, prevHead common.Hash) error
4142

4243
// Process crunches through the next header in the chain segment. The caller
4344
// will ensure a sequential order of headers.
44-
Process(header *types.Header)
45+
Process(ctx context.Context, header *types.Header) error
4546

4647
// Commit finalizes the section metadata and stores it into the database.
4748
Commit() error
@@ -71,9 +72,11 @@ type ChainIndexer struct {
7172
backend ChainIndexerBackend // Background processor generating the index data content
7273
children []*ChainIndexer // Child indexers to cascade chain updates to
7374

74-
active uint32 // Flag whether the event loop was started
75-
update chan struct{} // Notification channel that headers should be processed
76-
quit chan chan error // Quit channel to tear down running goroutines
75+
active uint32 // Flag whether the event loop was started
76+
update chan struct{} // Notification channel that headers should be processed
77+
quit chan chan error // Quit channel to tear down running goroutines
78+
ctx context.Context
79+
ctxCancel func()
7780

7881
sectionSize uint64 // Number of blocks in a single chain segment to process
7982
confirmsReq uint64 // Number of confirmations before processing a completed segment
@@ -105,6 +108,8 @@ func NewChainIndexer(chainDb, indexDb ethdb.Database, backend ChainIndexerBacken
105108
}
106109
// Initialize database dependent fields and start the updater
107110
c.loadValidSections()
111+
c.ctx, c.ctxCancel = context.WithCancel(context.Background())
112+
108113
go c.updateLoop()
109114

110115
return c
@@ -138,6 +143,8 @@ func (c *ChainIndexer) Start(chain ChainIndexerChain) {
138143
func (c *ChainIndexer) Close() error {
139144
var errs []error
140145

146+
c.ctxCancel()
147+
141148
// Tear down the primary update loop
142149
errc := make(chan error)
143150
c.quit <- errc
@@ -297,6 +304,12 @@ func (c *ChainIndexer) updateLoop() {
297304
c.lock.Unlock()
298305
newHead, err := c.processSection(section, oldHead)
299306
if err != nil {
307+
select {
308+
case <-c.ctx.Done():
309+
<-c.quit <- nil
310+
return
311+
default:
312+
}
300313
c.log.Error("Section processing failed", "error", err)
301314
}
302315
c.lock.Lock()
@@ -344,7 +357,7 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
344357

345358
// Reset and partial processing
346359

347-
if err := c.backend.Reset(section, lastHead); err != nil {
360+
if err := c.backend.Reset(c.ctx, section, lastHead); err != nil {
348361
c.setValidSections(0)
349362
return common.Hash{}, err
350363
}
@@ -360,11 +373,12 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
360373
} else if header.ParentHash != lastHead {
361374
return common.Hash{}, fmt.Errorf("chain reorged during section processing")
362375
}
363-
c.backend.Process(header)
376+
if err := c.backend.Process(c.ctx, header); err != nil {
377+
return common.Hash{}, err
378+
}
364379
lastHead = header.Hash()
365380
}
366381
if err := c.backend.Commit(); err != nil {
367-
c.log.Error("Section commit failed", "error", err)
368382
return common.Hash{}, err
369383
}
370384
return lastHead, nil

‎core/chain_indexer_test.go‎

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

1919
import (
20+
"context"
2021
"fmt"
2122
"math/big"
2223
"math/rand"
@@ -210,13 +211,13 @@ func (b *testChainIndexBackend) reorg(headNum uint64) uint64 {
210211
return b.stored * b.indexer.sectionSize
211212
}
212213

213-
func (b *testChainIndexBackend) Reset(section uint64, prevHead common.Hash) error {
214+
func (b *testChainIndexBackend) Reset(ctx context.Context, section uint64, prevHead common.Hash) error {
214215
b.section = section
215216
b.headerCnt = 0
216217
return nil
217218
}
218219

219-
func (b *testChainIndexBackend) Process(header *types.Header) {
220+
func (b *testChainIndexBackend) Process(ctx context.Context, header *types.Header) error {
220221
b.headerCnt++
221222
if b.headerCnt > b.indexer.sectionSize {
222223
b.t.Error("Processing too many headers")
@@ -227,6 +228,7 @@ func (b *testChainIndexBackend) Process(header *types.Header) {
227228
b.t.Fatal("Unexpected call to Process")
228229
case b.processCh <- header.Number.Uint64():
229230
}
231+
return nil
230232
}
231233

232234
func (b *testChainIndexBackend) Commit() error {

‎eth/backend.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
130130
gasPrice: config.GasPrice,
131131
etherbase: config.Etherbase,
132132
bloomRequests: make(chan chan *bloombits.Retrieval),
133-
bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks),
133+
bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, bloomConfirms),
134134
}
135135

136136
log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)

‎eth/bloombits.go‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package eth
1818

1919
import (
20+
"context"
2021
"time"
2122

2223
"github.com/ethereum/go-ethereum/common"
@@ -92,47 +93,45 @@ const (
9293
// BloomIndexer implements a core.ChainIndexer, building up a rotated bloom bits index
9394
// for the Ethereum header bloom filters, permitting blazing fast filtering.
9495
type BloomIndexer struct {
95-
size uint64 // section size to generate bloombits for
96-
97-
db ethdb.Database // database instance to write index data and metadata into
98-
gen *bloombits.Generator // generator to rotate the bloom bits crating the bloom index
99-
100-
section uint64 // Section is the section number being processed currently
101-
head common.Hash // Head is the hash of the last header processed
96+
size uint64 // section size to generate bloombits for
97+
db ethdb.Database // database instance to write index data and metadata into
98+
gen *bloombits.Generator // generator to rotate the bloom bits crating the bloom index
99+
section uint64 // Section is the section number being processed currently
100+
head common.Hash // Head is the hash of the last header processed
102101
}
103102

104103
// NewBloomIndexer returns a chain indexer that generates bloom bits data for the
105104
// canonical chain for fast logs filtering.
106-
func NewBloomIndexer(db ethdb.Database, size uint64) *core.ChainIndexer {
105+
func NewBloomIndexer(db ethdb.Database, size, confReq uint64) *core.ChainIndexer {
107106
backend := &BloomIndexer{
108107
db: db,
109108
size: size,
110109
}
111110
table := ethdb.NewTable(db, string(rawdb.BloomBitsIndexPrefix))
112111

113-
return core.NewChainIndexer(db, table, backend, size, bloomConfirms, bloomThrottling, "bloombits")
112+
return core.NewChainIndexer(db, table, backend, size, confReq, bloomThrottling, "bloombits")
114113
}
115114

116115
// Reset implements core.ChainIndexerBackend, starting a new bloombits index
117116
// section.
118-
func (b *BloomIndexer) Reset(section uint64, lastSectionHead common.Hash) error {
117+
func (b *BloomIndexer) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
119118
gen, err := bloombits.NewGenerator(uint(b.size))
120119
b.gen, b.section, b.head = gen, section, common.Hash{}
121120
return err
122121
}
123122

124123
// Process implements core.ChainIndexerBackend, adding a new header's bloom into
125124
// the index.
126-
func (b *BloomIndexer) Process(header *types.Header) {
125+
func (b *BloomIndexer) Process(ctx context.Context, header *types.Header) error {
127126
b.gen.AddBloom(uint(header.Number.Uint64()-b.section*b.size), header.Bloom)
128127
b.head = header.Hash()
128+
return nil
129129
}
130130

131131
// Commit implements core.ChainIndexerBackend, finalizing the bloom section and
132132
// writing it out into the database.
133133
func (b *BloomIndexer) Commit() error {
134134
batch := b.db.NewBatch()
135-
136135
for i := 0; i < types.BloomBitLength; i++ {
137136
bits, err := b.gen.Bitset(uint(i))
138137
if err != nil {

‎les/backend.go‎

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -95,29 +95,35 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
9595
quitSync := make(chan struct{})
9696

9797
leth := &LightEthereum{
98-
config: config,
99-
chainConfig: chainConfig,
100-
chainDb: chainDb,
101-
eventMux: ctx.EventMux,
102-
peers: peers,
103-
reqDist: newRequestDistributor(peers, quitSync),
104-
accountManager: ctx.AccountManager,
105-
engine: eth.CreateConsensusEngine(ctx, chainConfig, &config.Ethash, nil, chainDb),
106-
shutdownChan: make(chan bool),
107-
networkId: config.NetworkId,
108-
bloomRequests: make(chan chan *bloombits.Retrieval),
109-
bloomIndexer: eth.NewBloomIndexer(chainDb, light.BloomTrieFrequency),
110-
chtIndexer: light.NewChtIndexer(chainDb, true),
111-
bloomTrieIndexer: light.NewBloomTrieIndexer(chainDb, true),
98+
config: config,
99+
chainConfig: chainConfig,
100+
chainDb: chainDb,
101+
eventMux: ctx.EventMux,
102+
peers: peers,
103+
reqDist: newRequestDistributor(peers, quitSync),
104+
accountManager: ctx.AccountManager,
105+
engine: eth.CreateConsensusEngine(ctx, chainConfig, &config.Ethash, nil, chainDb),
106+
shutdownChan: make(chan bool),
107+
networkId: config.NetworkId,
108+
bloomRequests: make(chan chan *bloombits.Retrieval),
109+
bloomIndexer: eth.NewBloomIndexer(chainDb, light.BloomTrieFrequency, light.HelperTrieConfirmations),
112110
}
113111

114112
leth.relay = NewLesTxRelay(peers, leth.reqDist)
115113
leth.serverPool = newServerPool(chainDb, quitSync, &leth.wg)
116114
leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool)
117-
leth.odr = NewLesOdr(chainDb, leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer, leth.retriever)
115+
leth.odr = NewLesOdr(chainDb, leth.retriever)
116+
leth.chtIndexer = light.NewChtIndexer(chainDb, true, leth.odr)
117+
leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, true, leth.odr)
118+
leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
119+
// Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
120+
// indexers already set but not started yet
118121
if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine); err != nil {
119122
return nil, err
120123
}
124+
// Note: AddChildIndexer starts the update process for the child
125+
leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
126+
leth.chtIndexer.Start(leth.blockchain)
121127
leth.bloomIndexer.Start(leth.blockchain)
122128
// Rewind the chain in case of an incompatible config upgrade.
123129
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
@@ -242,9 +248,6 @@ func (s *LightEthereum) Stop() error {
242248
if s.chtIndexer != nil {
243249
s.chtIndexer.Close()
244250
}
245-
if s.bloomTrieIndexer != nil {
246-
s.bloomTrieIndexer.Close()
247-
}
248251
s.blockchain.Stop()
249252
s.protocolManager.Stop()
250253
s.txPool.Stop()

‎les/distributor.go‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,10 @@ package les
2020

2121
import (
2222
"container/list"
23-
"errors"
2423
"sync"
2524
"time"
2625
)
2726

28-
// ErrNoPeers is returned if no peers capable of serving a queued request are available
29-
var ErrNoPeers = errors.New("no suitable peers available")
30-
3127
// requestDistributor implements a mechanism that distributes requests to
3228
// suitable peers, obeying flow control rules and prioritizing them in creation
3329
// order (even when a resend is necessary).

‎les/handler.go‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1206,24 +1206,44 @@ func (pm *ProtocolManager) txStatus(hashes []common.Hash) []txStatus {
12061206
// NodeInfo represents a short summary of the Ethereum sub-protocol metadata
12071207
// known about the host peer.
12081208
type NodeInfo struct {
1209-
Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
1210-
Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
1211-
Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
1212-
Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules
1213-
Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
1209+
Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
1210+
Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
1211+
Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
1212+
Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules
1213+
Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
1214+
CHT light.TrustedCheckpoint `json:"cht"` // Trused CHT checkpoint for fast catchup
12141215
}
12151216

12161217
// NodeInfo retrieves some protocol metadata about the running host node.
12171218
func (self *ProtocolManager) NodeInfo() *NodeInfo {
12181219
head := self.blockchain.CurrentHeader()
12191220
hash := head.Hash()
12201221

1222+
var cht light.TrustedCheckpoint
1223+
1224+
sections, _, sectionHead := self.odr.ChtIndexer().Sections()
1225+
sections2, _, sectionHead2 := self.odr.BloomTrieIndexer().Sections()
1226+
if sections2 < sections {
1227+
sections = sections2
1228+
sectionHead = sectionHead2
1229+
}
1230+
if sections > 0 {
1231+
sectionIndex := sections - 1
1232+
cht = light.TrustedCheckpoint{
1233+
SectionIdx: sectionIndex,
1234+
SectionHead: sectionHead,
1235+
CHTRoot: light.GetChtRoot(self.chainDb, sectionIndex, sectionHead),
1236+
BloomRoot: light.GetBloomTrieRoot(self.chainDb, sectionIndex, sectionHead),
1237+
}
1238+
}
1239+
12211240
return &NodeInfo{
12221241
Network: self.networkId,
12231242
Difficulty: self.blockchain.GetTd(hash, head.Number.Uint64()),
12241243
Genesis: self.blockchain.Genesis().Hash(),
12251244
Config: self.blockchain.Config(),
12261245
Head: hash,
1246+
CHT: cht,
12271247
}
12281248
}
12291249

@@ -1258,7 +1278,7 @@ func (pc *peerConnection) RequestHeadersByHash(origin common.Hash, amount int, s
12581278
}
12591279
_, ok := <-pc.manager.reqDist.queue(rq)
12601280
if !ok {
1261-
return ErrNoPeers
1281+
return light.ErrNoPeers
12621282
}
12631283
return nil
12641284
}
@@ -1282,7 +1302,7 @@ func (pc *peerConnection) RequestHeadersByNumber(origin uint64, amount int, skip
12821302
}
12831303
_, ok := <-pc.manager.reqDist.queue(rq)
12841304
if !ok {
1285-
return ErrNoPeers
1305+
return light.ErrNoPeers
12861306
}
12871307
return nil
12881308
}

‎les/helper_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,12 @@ func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *cor
156156
} else {
157157
blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{})
158158

159-
chtIndexer := light.NewChtIndexer(db, false)
159+
chtIndexer := light.NewChtIndexer(db, false, nil)
160160
chtIndexer.Start(blockchain)
161161

162-
bbtIndexer := light.NewBloomTrieIndexer(db, false)
162+
bbtIndexer := light.NewBloomTrieIndexer(db, false, nil)
163163

164-
bloomIndexer := eth.NewBloomIndexer(db, params.BloomBitsBlocks)
164+
bloomIndexer := eth.NewBloomIndexer(db, params.BloomBitsBlocks, light.HelperTrieProcessConfirmations)
165165
bloomIndexer.AddChildIndexer(bbtIndexer)
166166
bloomIndexer.Start(blockchain)
167167

‎les/odr.go‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,11 @@ type LesOdr struct {
3333
stop chan struct{}
3434
}
3535

36-
func NewLesOdr(db ethdb.Database, chtIndexer, bloomTrieIndexer, bloomIndexer *core.ChainIndexer, retriever *retrieveManager) *LesOdr {
36+
func NewLesOdr(db ethdb.Database, retriever *retrieveManager) *LesOdr {
3737
return &LesOdr{
38-
db: db,
39-
chtIndexer: chtIndexer,
40-
bloomTrieIndexer: bloomTrieIndexer,
41-
bloomIndexer: bloomIndexer,
42-
retriever: retriever,
43-
stop: make(chan struct{}),
38+
db: db,
39+
retriever: retriever,
40+
stop: make(chan struct{}),
4441
}
4542
}
4643

@@ -54,6 +51,13 @@ func (odr *LesOdr) Database() ethdb.Database {
5451
return odr.db
5552
}
5653

54+
// SetIndexers adds the necessary chain indexers to the ODR backend
55+
func (odr *LesOdr) SetIndexers(chtIndexer, bloomTrieIndexer, bloomIndexer *core.ChainIndexer) {
56+
odr.chtIndexer = chtIndexer
57+
odr.bloomTrieIndexer = bloomTrieIndexer
58+
odr.bloomIndexer = bloomIndexer
59+
}
60+
5761
// ChtIndexer returns the CHT chain indexer
5862
func (odr *LesOdr) ChtIndexer() *core.ChainIndexer {
5963
return odr.chtIndexer

0 commit comments

Comments
 (0)