Skip to content

Commit e5ff2cd

Browse files
committed
les: handler separation
1 parent 962af9f commit e5ff2cd

31 files changed

+2203
-2481
lines changed

les/api.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -170,15 +170,17 @@ type priorityClientInfo struct {
170170
}
171171

172172
// newPriorityClientPool creates a new priority client pool
173-
func newPriorityClientPool(freeClientCap uint64, ps *peerSet, child clientPool, metricsLogger, eventLogger *csvlogger.Logger) *priorityClientPool {
174-
return &priorityClientPool{
173+
func newPriorityClientPool(freeClientCap uint64, ps *peerSet, child clientPool, eventLogger *csvlogger.Logger, metricsLogger *csvlogger.Logger) *priorityClientPool {
174+
pool := &priorityClientPool{
175175
clients: make(map[enode.ID]priorityClientInfo),
176176
freeClientCap: freeClientCap,
177177
ps: ps,
178178
child: child,
179179
logger: eventLogger,
180180
logTotalPriConn: metricsLogger.NewChannel("totalPriConn", 0),
181181
}
182+
ps.notify(pool)
183+
return pool
182184
}
183185

184186
// registerPeer is called when a new client is connected. If the client has no
@@ -456,7 +458,7 @@ func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, pas
456458
return nil, ErrUnknownBenchmarkType
457459
}
458460
}
459-
rs := api.server.protocolManager.runBenchmark(benchmarks, passCount, time.Millisecond*time.Duration(length))
461+
rs := api.server.handler.runBenchmark(benchmarks, passCount, time.Millisecond*time.Duration(length))
460462
result := make([]map[string]interface{}, len(setups))
461463
for i, r := range rs {
462464
res := make(map[string]interface{})
@@ -476,14 +478,12 @@ func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, pas
476478
// PrivateLightAPI provides an API to access the LES light server or light client.
477479
type PrivateLightAPI struct {
478480
backend *lesCommons
479-
reg *checkpointRegistrar
480481
}
481482

482483
// NewPrivateLightAPI creates a new LES service API.
483-
func NewPrivateLightAPI(backend *lesCommons, reg *checkpointRegistrar) *PrivateLightAPI {
484+
func NewPrivateLightAPI(backend *lesCommons) *PrivateLightAPI {
484485
return &PrivateLightAPI{
485486
backend: backend,
486-
reg: reg,
487487
}
488488
}
489489

@@ -513,7 +513,7 @@ func (api *PrivateLightAPI) LatestCheckpoint() ([4]string, error) {
513513
// result[2], 32 bytes hex encoded latest section bloom trie root hash
514514
func (api *PrivateLightAPI) GetCheckpoint(index uint64) ([3]string, error) {
515515
var res [3]string
516-
cp := api.backend.getLocalCheckpoint(index)
516+
cp := api.backend.localCheckpoint(index)
517517
if cp.Empty() {
518518
return res, ErrNoCheckpoint
519519
}
@@ -523,8 +523,8 @@ func (api *PrivateLightAPI) GetCheckpoint(index uint64) ([3]string, error) {
523523

524524
// GetCheckpointContractAddress returns the contract contract address in hex format.
525525
func (api *PrivateLightAPI) GetCheckpointContractAddress() (string, error) {
526-
if api.reg == nil {
526+
if api.backend.registrar == nil {
527527
return "", ErrNotActivated
528528
}
529-
return api.reg.config.ContractAddr.Hex(), nil
529+
return api.backend.registrar.config.ContractAddr.Hex(), nil
530530
}

les/api_backend.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ func (b *LesApiBackend) CurrentBlock() *types.Block {
5454
}
5555

5656
func (b *LesApiBackend) SetHead(number uint64) {
57-
b.eth.protocolManager.downloader.Cancel()
57+
b.eth.handler.downloader.Cancel()
5858
b.eth.blockchain.SetHead(number)
5959
}
6060

les/api_test.go

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -79,19 +79,16 @@ func TestCapacityAPI10(t *testing.T) {
7979
// while connected and going back and forth between free and priority mode with
8080
// the supplied API calls is also thoroughly tested.
8181
func testCapacityAPI(t *testing.T, clientCount int) {
82+
// Skip test if no data dir specified
8283
if testServerDataDir == "" {
83-
// Skip test if no data dir specified
8484
return
8585
}
86-
8786
for !testSim(t, 1, clientCount, []string{testServerDataDir}, nil, func(ctx context.Context, net *simulations.Network, servers []*simulations.Node, clients []*simulations.Node) bool {
8887
if len(servers) != 1 {
8988
t.Fatalf("Invalid number of servers: %d", len(servers))
9089
}
9190
server := servers[0]
9291

93-
clientRpcClients := make([]*rpc.Client, len(clients))
94-
9592
serverRpcClient, err := server.Client()
9693
if err != nil {
9794
t.Fatalf("Failed to obtain rpc client: %v", err)
@@ -101,6 +98,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
10198
minCap := getMinCap(ctx, t, serverRpcClient)
10299
testCap := totalCap * 3 / 4
103100
fmt.Printf("Server testCap: %d minCap: %d head number: %d head hash: %064x\n", testCap, minCap, headNum, headHash)
101+
104102
reqMinCap := uint64(float64(testCap) * minRelCap / (minRelCap + float64(len(clients)-1)))
105103
if minCap > reqMinCap {
106104
t.Fatalf("Minimum client capacity (%d) bigger than required minimum for this test (%d)", minCap, reqMinCap)
@@ -109,13 +107,13 @@ func testCapacityAPI(t *testing.T, clientCount int) {
109107
freeIdx := rand.Intn(len(clients))
110108
freeCap := getFreeCap(ctx, t, serverRpcClient)
111109

110+
clientRpcClients := make([]*rpc.Client, len(clients))
112111
for i, client := range clients {
113112
var err error
114113
clientRpcClients[i], err = client.Client()
115114
if err != nil {
116115
t.Fatalf("Failed to obtain rpc client: %v", err)
117116
}
118-
119117
fmt.Println("connecting client", i)
120118
if i != freeIdx {
121119
setCapacity(ctx, t, serverRpcClient, client.ID(), testCap/uint64(len(clients)))
@@ -142,21 +140,22 @@ func testCapacityAPI(t *testing.T, clientCount int) {
142140

143141
reqCount := make([]uint64, len(clientRpcClients))
144142

143+
// Send light request like crazy.
145144
for i, c := range clientRpcClients {
146145
wg.Add(1)
147146
i, c := i, c
148147
go func() {
148+
defer wg.Done()
149+
149150
queue := make(chan struct{}, 100)
150151
var count uint64
151152
for {
152153
select {
153154
case queue <- struct{}{}:
154155
select {
155156
case <-stop:
156-
wg.Done()
157157
return
158158
case <-ctx.Done():
159-
wg.Done()
160159
return
161160
default:
162161
wg.Add(1)
@@ -171,10 +170,8 @@ func testCapacityAPI(t *testing.T, clientCount int) {
171170
}()
172171
}
173172
case <-stop:
174-
wg.Done()
175173
return
176174
case <-ctx.Done():
177-
wg.Done()
178175
return
179176
}
180177
}
@@ -315,12 +312,10 @@ func getHead(ctx context.Context, t *testing.T, client *rpc.Client) (uint64, com
315312
}
316313

317314
func testRequest(ctx context.Context, t *testing.T, client *rpc.Client) bool {
318-
//res := make(map[string]interface{})
319315
var res string
320316
var addr common.Address
321317
rand.Read(addr[:])
322318
c, _ := context.WithTimeout(ctx, time.Second*12)
323-
// if err := client.CallContext(ctx, &res, "eth_getProof", addr, nil, "latest"); err != nil {
324319
err := client.CallContext(c, &res, "eth_getBalance", addr, "latest")
325320
if err != nil {
326321
fmt.Println("request error:", err)
@@ -417,7 +412,6 @@ func NewNetwork() (*simulations.Network, func(), error) {
417412
adapterTeardown()
418413
net.Shutdown()
419414
}
420-
421415
return net, teardown, nil
422416
}
423417

@@ -515,7 +509,6 @@ func newLesServerService(ctx *adapters.ServiceContext) (node.Service, error) {
515509
if err != nil {
516510
return nil, err
517511
}
518-
519512
server, err := NewLesServer(ethereum, &config)
520513
if err != nil {
521514
return nil, err

les/benchmark.go

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import (
3939
// requestBenchmark is an interface for different randomized request generators
4040
type requestBenchmark interface {
4141
// init initializes the generator for generating the given number of randomized requests
42-
init(pm *ProtocolManager, count int) error
42+
init(h *serverHandler, count int) error
4343
// request initiates sending a single request to the given peer
4444
request(peer *peer, index int) error
4545
}
@@ -52,10 +52,10 @@ type benchmarkBlockHeaders struct {
5252
hashes []common.Hash
5353
}
5454

55-
func (b *benchmarkBlockHeaders) init(pm *ProtocolManager, count int) error {
55+
func (b *benchmarkBlockHeaders) init(h *serverHandler, count int) error {
5656
d := int64(b.amount-1) * int64(b.skip+1)
5757
b.offset = 0
58-
b.randMax = pm.blockchain.CurrentHeader().Number.Int64() + 1 - d
58+
b.randMax = h.blockchain.CurrentHeader().Number.Int64() + 1 - d
5959
if b.randMax < 0 {
6060
return fmt.Errorf("chain is too short")
6161
}
@@ -65,7 +65,7 @@ func (b *benchmarkBlockHeaders) init(pm *ProtocolManager, count int) error {
6565
if b.byHash {
6666
b.hashes = make([]common.Hash, count)
6767
for i := range b.hashes {
68-
b.hashes[i] = rawdb.ReadCanonicalHash(pm.chainDb, uint64(b.offset+rand.Int63n(b.randMax)))
68+
b.hashes[i] = rawdb.ReadCanonicalHash(h.chainDb, uint64(b.offset+rand.Int63n(b.randMax)))
6969
}
7070
}
7171
return nil
@@ -85,11 +85,11 @@ type benchmarkBodiesOrReceipts struct {
8585
hashes []common.Hash
8686
}
8787

88-
func (b *benchmarkBodiesOrReceipts) init(pm *ProtocolManager, count int) error {
89-
randMax := pm.blockchain.CurrentHeader().Number.Int64() + 1
88+
func (b *benchmarkBodiesOrReceipts) init(h *serverHandler, count int) error {
89+
randMax := h.blockchain.CurrentHeader().Number.Int64() + 1
9090
b.hashes = make([]common.Hash, count)
9191
for i := range b.hashes {
92-
b.hashes[i] = rawdb.ReadCanonicalHash(pm.chainDb, uint64(rand.Int63n(randMax)))
92+
b.hashes[i] = rawdb.ReadCanonicalHash(h.chainDb, uint64(rand.Int63n(randMax)))
9393
}
9494
return nil
9595
}
@@ -108,8 +108,8 @@ type benchmarkProofsOrCode struct {
108108
headHash common.Hash
109109
}
110110

111-
func (b *benchmarkProofsOrCode) init(pm *ProtocolManager, count int) error {
112-
b.headHash = pm.blockchain.CurrentHeader().Hash()
111+
func (b *benchmarkProofsOrCode) init(h *serverHandler, count int) error {
112+
b.headHash = h.blockchain.CurrentHeader().Hash()
113113
return nil
114114
}
115115

@@ -130,11 +130,11 @@ type benchmarkHelperTrie struct {
130130
sectionCount, headNum uint64
131131
}
132132

133-
func (b *benchmarkHelperTrie) init(pm *ProtocolManager, count int) error {
133+
func (b *benchmarkHelperTrie) init(h *serverHandler, count int) error {
134134
if b.bloom {
135-
b.sectionCount, b.headNum, _ = pm.server.bloomTrieIndexer.Sections()
135+
b.sectionCount, b.headNum, _ = h.server.bloomTrieIndexer.Sections()
136136
} else {
137-
b.sectionCount, _, _ = pm.server.chtIndexer.Sections()
137+
b.sectionCount, _, _ = h.server.chtIndexer.Sections()
138138
b.headNum = b.sectionCount*params.CHTFrequency - 1
139139
}
140140
if b.sectionCount == 0 {
@@ -170,7 +170,7 @@ type benchmarkTxSend struct {
170170
txs types.Transactions
171171
}
172172

173-
func (b *benchmarkTxSend) init(pm *ProtocolManager, count int) error {
173+
func (b *benchmarkTxSend) init(h *serverHandler, count int) error {
174174
key, _ := crypto.GenerateKey()
175175
addr := crypto.PubkeyToAddress(key.PublicKey)
176176
signer := types.NewEIP155Signer(big.NewInt(18))
@@ -196,7 +196,7 @@ func (b *benchmarkTxSend) request(peer *peer, index int) error {
196196
// benchmarkTxStatus implements requestBenchmark
197197
type benchmarkTxStatus struct{}
198198

199-
func (b *benchmarkTxStatus) init(pm *ProtocolManager, count int) error {
199+
func (b *benchmarkTxStatus) init(h *serverHandler, count int) error {
200200
return nil
201201
}
202202

@@ -217,7 +217,7 @@ type benchmarkSetup struct {
217217

218218
// runBenchmark runs a benchmark cycle for all benchmark types in the specified
219219
// number of passes
220-
func (pm *ProtocolManager) runBenchmark(benchmarks []requestBenchmark, passCount int, targetTime time.Duration) []*benchmarkSetup {
220+
func (h *serverHandler) runBenchmark(benchmarks []requestBenchmark, passCount int, targetTime time.Duration) []*benchmarkSetup {
221221
setup := make([]*benchmarkSetup, len(benchmarks))
222222
for i, b := range benchmarks {
223223
setup[i] = &benchmarkSetup{req: b}
@@ -239,7 +239,7 @@ func (pm *ProtocolManager) runBenchmark(benchmarks []requestBenchmark, passCount
239239
if next.totalTime > 0 {
240240
count = int(uint64(next.totalCount) * uint64(targetTime) / uint64(next.totalTime))
241241
}
242-
if err := pm.measure(next, count); err != nil {
242+
if err := h.measure(next, count); err != nil {
243243
next.err = err
244244
}
245245
}
@@ -275,14 +275,15 @@ func (m *meteredPipe) WriteMsg(msg p2p.Msg) error {
275275

276276
// measure runs a benchmark for a single type in a single pass, with the given
277277
// number of requests
278-
func (pm *ProtocolManager) measure(setup *benchmarkSetup, count int) error {
278+
func (h *serverHandler) measure(setup *benchmarkSetup, count int) error {
279279
clientPipe, serverPipe := p2p.MsgPipe()
280280
clientMeteredPipe := &meteredPipe{rw: clientPipe}
281281
serverMeteredPipe := &meteredPipe{rw: serverPipe}
282282
var id enode.ID
283283
rand.Read(id[:])
284-
clientPeer := pm.newPeer(lpv2, NetworkId, p2p.NewPeer(id, "client", nil), clientMeteredPipe)
285-
serverPeer := pm.newPeer(lpv2, NetworkId, p2p.NewPeer(id, "server", nil), serverMeteredPipe)
284+
285+
clientPeer := newPeer(lpv2, NetworkId, false, p2p.NewPeer(id, "client", nil), clientMeteredPipe)
286+
serverPeer := newPeer(lpv2, NetworkId, false, p2p.NewPeer(id, "server", nil), serverMeteredPipe)
286287
serverPeer.sendQueue = newExecQueue(count)
287288
serverPeer.announceType = announceTypeNone
288289
serverPeer.fcCosts = make(requestCostTable)
@@ -291,10 +292,10 @@ func (pm *ProtocolManager) measure(setup *benchmarkSetup, count int) error {
291292
serverPeer.fcCosts[code] = c
292293
}
293294
serverPeer.fcParams = flowcontrol.ServerParams{BufLimit: 1, MinRecharge: 1}
294-
serverPeer.fcClient = flowcontrol.NewClientNode(pm.server.fcManager, serverPeer.fcParams)
295+
serverPeer.fcClient = flowcontrol.NewClientNode(h.server.fcManager, serverPeer.fcParams)
295296
defer serverPeer.fcClient.Disconnect()
296297

297-
if err := setup.req.init(pm, count); err != nil {
298+
if err := setup.req.init(h, count); err != nil {
298299
return err
299300
}
300301

@@ -311,7 +312,7 @@ func (pm *ProtocolManager) measure(setup *benchmarkSetup, count int) error {
311312
}()
312313
go func() {
313314
for i := 0; i < count; i++ {
314-
if err := pm.handleMsg(serverPeer); err != nil {
315+
if err := h.handleMsg(serverPeer); err != nil {
315316
errCh <- err
316317
return
317318
}
@@ -336,7 +337,7 @@ func (pm *ProtocolManager) measure(setup *benchmarkSetup, count int) error {
336337
if err != nil {
337338
return err
338339
}
339-
case <-pm.quitSync:
340+
case <-h.closeCh:
340341
clientPipe.Close()
341342
serverPipe.Close()
342343
return fmt.Errorf("Benchmark cancelled")

les/bloombits.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,10 @@ const (
4646
func (eth *LightEthereum) startBloomHandlers(sectionSize uint64) {
4747
for i := 0; i < bloomServiceThreads; i++ {
4848
go func() {
49+
defer eth.wg.Done()
4950
for {
5051
select {
51-
case <-eth.shutdownChan:
52+
case <-eth.closeCh:
5253
return
5354

5455
case request := <-eth.bloomRequests:

0 commit comments

Comments
 (0)