Skip to content

Commit 9f8d192

Browse files
zsfelfoldifjl
authored andcommitted
les: light client protocol and API
1 parent 760fd65 commit 9f8d192

41 files changed

Lines changed: 5860 additions & 33 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎common/mclock/mclock.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Copyright 2016 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
// package mclock is a wrapper for a monotonic clock source
18+
package mclock
19+
20+
import (
21+
"time"
22+
23+
"github.com/aristanetworks/goarista/monotime"
24+
)
25+
26+
type AbsTime time.Duration // absolute monotonic time
27+
28+
func Now() AbsTime {
29+
return AbsTime(monotime.Now())
30+
}

‎eth/api_backend.go‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,17 @@ func (b *EthApiBackend) SetHead(number uint64) {
4444
b.eth.blockchain.SetHead(number)
4545
}
4646

47-
func (b *EthApiBackend) HeaderByNumber(blockNr rpc.BlockNumber) *types.Header {
47+
func (b *EthApiBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) {
4848
// Pending block is only known by the miner
4949
if blockNr == rpc.PendingBlockNumber {
5050
block, _ := b.eth.miner.Pending()
51-
return block.Header()
51+
return block.Header(), nil
5252
}
5353
// Otherwise resolve and return the block
5454
if blockNr == rpc.LatestBlockNumber {
55-
return b.eth.blockchain.CurrentBlock().Header()
55+
return b.eth.blockchain.CurrentBlock().Header(), nil
5656
}
57-
return b.eth.blockchain.GetHeaderByNumber(uint64(blockNr))
57+
return b.eth.blockchain.GetHeaderByNumber(uint64(blockNr)), nil
5858
}
5959

6060
func (b *EthApiBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error) {
@@ -70,16 +70,16 @@ func (b *EthApiBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumb
7070
return b.eth.blockchain.GetBlockByNumber(uint64(blockNr)), nil
7171
}
7272

73-
func (b *EthApiBackend) StateAndHeaderByNumber(blockNr rpc.BlockNumber) (ethapi.State, *types.Header, error) {
73+
func (b *EthApiBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (ethapi.State, *types.Header, error) {
7474
// Pending state is only known by the miner
7575
if blockNr == rpc.PendingBlockNumber {
7676
block, state := b.eth.miner.Pending()
7777
return EthApiState{state}, block.Header(), nil
7878
}
7979
// Otherwise resolve the block number and return its state
80-
header := b.HeaderByNumber(blockNr)
81-
if header == nil {
82-
return nil, nil, nil
80+
header, err := b.HeaderByNumber(ctx, blockNr)
81+
if header == nil || err != nil {
82+
return nil, nil, err
8383
}
8484
stateDb, err := b.eth.BlockChain().StateAt(header.Root)
8585
return EthApiState{stateDb}, header, err

‎eth/backend.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ func (s *Ethereum) APIs() []rpc.API {
312312
}, {
313313
Namespace: "eth",
314314
Version: "1.0",
315-
Service: filters.NewPublicFilterAPI(s.chainDb, s.eventMux),
315+
Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
316316
Public: true,
317317
}, {
318318
Namespace: "admin",

‎eth/filters/api.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,14 @@ type PublicFilterAPI struct {
6161
}
6262

6363
// NewPublicFilterAPI returns a new PublicFilterAPI instance.
64-
func NewPublicFilterAPI(chainDb ethdb.Database, mux *event.TypeMux) *PublicFilterAPI {
64+
func NewPublicFilterAPI(backend Backend, lightMode bool) *PublicFilterAPI {
6565
api := &PublicFilterAPI{
66-
mux: mux,
67-
chainDb: chainDb,
68-
events: NewEventSystem(mux),
69-
filters: make(map[rpc.ID]*filter),
66+
backend: backend,
67+
useMipMap: !lightMode,
68+
mux: backend.EventMux(),
69+
chainDb: backend.ChainDb(),
70+
events: NewEventSystem(backend.EventMux(), backend, lightMode),
71+
filters: make(map[rpc.ID]*filter),
7072
}
7173

7274
go api.timeoutLoop()

‎eth/filters/filter.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,15 @@ Logs:
207207
return ret
208208
}
209209

210-
func (f *Filter) bloomFilter(block *types.Block) bool {
211-
if len(f.addresses) > 0 {
210+
func (f *Filter) bloomFilter(bloom types.Bloom) bool {
211+
return bloomFilter(bloom, f.addresses, f.topics)
212+
}
213+
214+
func bloomFilter(bloom types.Bloom, addresses []common.Address, topics [][]common.Hash) bool {
215+
if len(addresses) > 0 {
212216
var included bool
213-
for _, addr := range f.addresses {
214-
if types.BloomLookup(block.Bloom(), addr) {
217+
for _, addr := range addresses {
218+
if types.BloomLookup(bloom, addr) {
215219
included = true
216220
break
217221
}
@@ -222,7 +226,7 @@ func (f *Filter) bloomFilter(block *types.Block) bool {
222226
}
223227
}
224228

225-
for _, sub := range f.topics {
229+
for _, sub := range topics {
226230
var included bool
227231
for _, topic := range sub {
228232
if (topic == common.Hash{}) || types.BloomLookup(block.Bloom(), topic) {

‎eth/filters/filter_system.go‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import (
3131
"github.com/ethereum/go-ethereum/core/vm"
3232
"github.com/ethereum/go-ethereum/event"
3333
"github.com/ethereum/go-ethereum/rpc"
34+
"golang.org/x/net/context"
3435
)
3536

3637
// Type determines the kind of filter and is used to put the filter in to
@@ -95,6 +96,9 @@ type subscription struct {
9596
type EventSystem struct {
9697
mux *event.TypeMux
9798
sub event.Subscription
99+
backend Backend
100+
lightMode bool
101+
lastHead *types.Header
98102
install chan *subscription // install filter for event notification
99103
uninstall chan *subscription // remove filter for event notification
100104
}
@@ -105,9 +109,11 @@ type EventSystem struct {
105109
//
106110
// The returned manager has a loop that needs to be stopped with the Stop function
107111
// or by stopping the given mux.
108-
func NewEventSystem(mux *event.TypeMux) *EventSystem {
112+
func NewEventSystem(mux *event.TypeMux, backend Backend, lightMode bool) *EventSystem {
109113
m := &EventSystem{
110114
mux: mux,
115+
backend: backend,
116+
lightMode: lightMode,
111117
install: make(chan *subscription),
112118
uninstall: make(chan *subscription),
113119
}
@@ -235,7 +241,7 @@ func (es *EventSystem) SubscribeNewHeads(headers chan *types.Header) *Subscripti
235241
type filterIndex map[Type]map[rpc.ID]*subscription
236242

237243
// broadcast event to filters that match criteria.
238-
func broadcast(filters filterIndex, ev *event.Event) {
244+
func (es *EventSystem) broadcast(filters filterIndex, ev *event.Event) {
239245
if ev == nil {
240246
return
241247
}
@@ -279,7 +285,77 @@ func broadcast(filters filterIndex, ev *event.Event) {
279285
f.headers <- e.Block.Header()
280286
}
281287
}
288+
if es.lightMode && len(filters[LogsSubscription]) > 0 {
289+
es.lightFilterNewHead(e.Block.Header(), func(header *types.Header, remove bool) {
290+
for _, f := range filters[LogsSubscription] {
291+
if ev.Time.After(f.created) {
292+
if matchedLogs := es.lightFilterLogs(header, f.logsCrit.Addresses, f.logsCrit.Topics, remove); len(matchedLogs) > 0 {
293+
f.logs <- matchedLogs
294+
}
295+
}
296+
}
297+
})
298+
}
299+
}
300+
}
301+
302+
func (es *EventSystem) lightFilterNewHead(newHeader *types.Header, callBack func(*types.Header, bool)) {
303+
oldh := es.lastHead
304+
es.lastHead = newHeader
305+
if oldh == nil {
306+
return
307+
}
308+
newh := newHeader
309+
// find common ancestor, create list of rolled back and new block hashes
310+
var oldHeaders, newHeaders []*types.Header
311+
for oldh.Hash() != newh.Hash() {
312+
if oldh.GetNumberU64() >= newh.GetNumberU64() {
313+
oldHeaders = append(oldHeaders, oldh)
314+
oldh = core.GetHeader(es.backend.ChainDb(), oldh.ParentHash, oldh.Number.Uint64()-1)
315+
}
316+
if oldh.GetNumberU64() < newh.GetNumberU64() {
317+
newHeaders = append(newHeaders, newh)
318+
newh = core.GetHeader(es.backend.ChainDb(), newh.ParentHash, newh.Number.Uint64()-1)
319+
if newh == nil {
320+
// happens when CHT syncing, nothing to do
321+
newh = oldh
322+
}
323+
}
324+
}
325+
// roll back old blocks
326+
for _, h := range oldHeaders {
327+
callBack(h, true)
328+
}
329+
// check new blocks (array is in reverse order)
330+
for i := len(newHeaders) - 1; i >= 0; i-- {
331+
callBack(newHeaders[i], false)
332+
}
333+
}
334+
335+
// filter logs of a single header in light client mode
336+
func (es *EventSystem) lightFilterLogs(header *types.Header, addresses []common.Address, topics [][]common.Hash, remove bool) []Log {
337+
//fmt.Println("lightFilterLogs", header.Number.Uint64(), remove)
338+
if bloomFilter(header.Bloom, addresses, topics) {
339+
//fmt.Println("bloom match")
340+
// Get the logs of the block
341+
ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
342+
receipts, err := es.backend.GetReceipts(ctx, header.Hash())
343+
if err != nil {
344+
return nil
345+
}
346+
var unfiltered []Log
347+
for _, receipt := range receipts {
348+
rl := make([]Log, len(receipt.Logs))
349+
for i, l := range receipt.Logs {
350+
rl[i] = Log{l, remove}
351+
}
352+
unfiltered = append(unfiltered, rl...)
353+
}
354+
logs := filterLogs(unfiltered, addresses, topics)
355+
//fmt.Println("found", len(logs))
356+
return logs
282357
}
358+
return nil
283359
}
284360

285361
// eventLoop (un)installs filters and processes mux events.
@@ -294,7 +370,7 @@ func (es *EventSystem) eventLoop() {
294370
if !active { // system stopped
295371
return
296372
}
297-
broadcast(index, ev)
373+
es.broadcast(index, ev)
298374
case f := <-es.install:
299375
if _, found := index[f.typ]; !found {
300376
index[f.typ] = make(map[rpc.ID]*subscription)

‎eth/filters/filter_system_test.go‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@ import (
3232
)
3333

3434
var (
35-
mux = new(event.TypeMux)
36-
db, _ = ethdb.NewMemDatabase()
37-
api = NewPublicFilterAPI(db, mux)
35+
mux = new(event.TypeMux)
36+
db, _ = ethdb.NewMemDatabase()
37+
backend = &testBackend{mux, db}
38+
api = NewPublicFilterAPI(backend, false)
3839
)
3940

4041
// TestBlockSubscription tests if a block subscription returns block hashes for posted chain events.

0 commit comments

Comments
 (0)