Skip to content

Commit 9effd64

Browse files
authored
core, eth, trie: bloom filter for trie node dedup during fast sync (#19489)
* core, eth, trie: bloom filter for trie node dedup during fast sync * eth/downloader, trie: address review comments * core, ethdb, trie: restart fast-sync bloom construction now and again * eth/downloader: initialize fast sync bloom on startup * eth: reenable eth/62 until we properly remove it
1 parent 40cdcf8 commit 9effd64

46 files changed

Lines changed: 2668 additions & 57 deletions

Some content is hidden

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

‎cmd/geth/chaincmd.go‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535
"github.com/ethereum/go-ethereum/eth/downloader"
3636
"github.com/ethereum/go-ethereum/event"
3737
"github.com/ethereum/go-ethereum/log"
38+
"github.com/ethereum/go-ethereum/trie"
3839
"gopkg.in/urfave/cli.v1"
3940
)
4041

@@ -375,11 +376,16 @@ func copyDb(ctx *cli.Context) error {
375376
defer stack.Close()
376377

377378
chain, chainDb := utils.MakeChain(ctx, stack)
378-
syncmode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
379-
dl := downloader.New(syncmode, 0, chainDb, new(event.TypeMux), chain, nil, nil)
379+
syncMode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
380+
381+
var syncBloom *trie.SyncBloom
382+
if syncMode == downloader.FastSync {
383+
syncBloom = trie.NewSyncBloom(uint64(ctx.GlobalInt(utils.CacheFlag.Name)/2), chainDb)
384+
}
385+
dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
380386

381387
// Create a source peer to satisfy downloader requests from
382-
db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name), 256, "")
388+
db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, "")
383389
if err != nil {
384390
return err
385391
}
@@ -395,7 +401,7 @@ func copyDb(ctx *cli.Context) error {
395401
start := time.Now()
396402

397403
currentHeader := hc.CurrentHeader()
398-
if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncmode); err != nil {
404+
if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncMode); err != nil {
399405
return err
400406
}
401407
for dl.Synchronising() {

‎core/rawdb/table.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,13 @@ func (t *table) NewIterator() ethdb.Iterator {
6767
return t.NewIteratorWithPrefix(nil)
6868
}
6969

70+
// NewIteratorWithStart creates a binary-alphabetical iterator over a subset of
71+
// database content starting at a particular initial key (or after, if it does
72+
// not exist).
73+
func (t *table) NewIteratorWithStart(start []byte) ethdb.Iterator {
74+
return t.db.NewIteratorWithStart(start)
75+
}
76+
7077
// NewIteratorWithPrefix creates a binary-alphabetical iterator over a subset
7178
// of database content with a particular key prefix.
7279
func (t *table) NewIteratorWithPrefix(prefix []byte) ethdb.Iterator {

‎core/state/sync.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import (
2626
)
2727

2828
// NewStateSync create a new state trie download scheduler.
29-
func NewStateSync(root common.Hash, database ethdb.Reader) *trie.Sync {
29+
func NewStateSync(root common.Hash, database ethdb.Reader, bloom *trie.SyncBloom) *trie.Sync {
3030
var syncer *trie.Sync
3131
callback := func(leaf []byte, parent common.Hash) error {
3232
var obj Account
@@ -37,6 +37,6 @@ func NewStateSync(root common.Hash, database ethdb.Reader) *trie.Sync {
3737
syncer.AddRawEntry(common.BytesToHash(obj.CodeHash), 64, parent)
3838
return nil
3939
}
40-
syncer = trie.NewSync(root, database, callback)
40+
syncer = trie.NewSync(root, database, callback, bloom)
4141
return syncer
4242
}

‎core/state/sync_test.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/ethereum/go-ethereum/core/rawdb"
2626
"github.com/ethereum/go-ethereum/crypto"
2727
"github.com/ethereum/go-ethereum/ethdb"
28+
"github.com/ethereum/go-ethereum/ethdb/memorydb"
2829
"github.com/ethereum/go-ethereum/trie"
2930
)
3031

@@ -125,7 +126,7 @@ func checkStateConsistency(db ethdb.Database, root common.Hash) error {
125126
// Tests that an empty state is not scheduled for syncing.
126127
func TestEmptyStateSync(t *testing.T) {
127128
empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
128-
if req := NewStateSync(empty, rawdb.NewMemoryDatabase()).Missing(1); len(req) != 0 {
129+
if req := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New())).Missing(1); len(req) != 0 {
129130
t.Errorf("content requested for empty state: %v", req)
130131
}
131132
}
@@ -141,7 +142,7 @@ func testIterativeStateSync(t *testing.T, batch int) {
141142

142143
// Create a destination state and sync with the scheduler
143144
dstDb := rawdb.NewMemoryDatabase()
144-
sched := NewStateSync(srcRoot, dstDb)
145+
sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
145146

146147
queue := append([]common.Hash{}, sched.Missing(batch)...)
147148
for len(queue) > 0 {
@@ -173,7 +174,7 @@ func TestIterativeDelayedStateSync(t *testing.T) {
173174

174175
// Create a destination state and sync with the scheduler
175176
dstDb := rawdb.NewMemoryDatabase()
176-
sched := NewStateSync(srcRoot, dstDb)
177+
sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
177178

178179
queue := append([]common.Hash{}, sched.Missing(0)...)
179180
for len(queue) > 0 {
@@ -210,7 +211,7 @@ func testIterativeRandomStateSync(t *testing.T, batch int) {
210211

211212
// Create a destination state and sync with the scheduler
212213
dstDb := rawdb.NewMemoryDatabase()
213-
sched := NewStateSync(srcRoot, dstDb)
214+
sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
214215

215216
queue := make(map[common.Hash]struct{})
216217
for _, hash := range sched.Missing(batch) {
@@ -250,7 +251,7 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
250251

251252
// Create a destination state and sync with the scheduler
252253
dstDb := rawdb.NewMemoryDatabase()
253-
sched := NewStateSync(srcRoot, dstDb)
254+
sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
254255

255256
queue := make(map[common.Hash]struct{})
256257
for _, hash := range sched.Missing(0) {
@@ -297,7 +298,7 @@ func TestIncompleteStateSync(t *testing.T) {
297298

298299
// Create a destination state and sync with the scheduler
299300
dstDb := rawdb.NewMemoryDatabase()
300-
sched := NewStateSync(srcRoot, dstDb)
301+
sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
301302

302303
added := []common.Hash{}
303304
queue := append([]common.Hash{}, sched.Missing(1)...)

‎eth/backend.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,10 +190,11 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
190190
}
191191
eth.txPool = core.NewTxPool(config.TxPool, chainConfig, eth.blockchain)
192192

193-
if eth.protocolManager, err = NewProtocolManager(chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, config.Whitelist); err != nil {
193+
// Permit the downloader to use the trie cache allowance during fast sync
194+
cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit
195+
if eth.protocolManager, err = NewProtocolManager(chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist); err != nil {
194196
return nil, err
195197
}
196-
197198
eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock)
198199
eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
199200

‎eth/downloader/downloader.go‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434
"github.com/ethereum/go-ethereum/log"
3535
"github.com/ethereum/go-ethereum/metrics"
3636
"github.com/ethereum/go-ethereum/params"
37+
"github.com/ethereum/go-ethereum/trie"
3738
)
3839

3940
var (
@@ -104,7 +105,9 @@ type Downloader struct {
104105
genesis uint64 // Genesis block number to limit sync to (e.g. light client CHT)
105106
queue *queue // Scheduler for selecting the hashes to download
106107
peers *peerSet // Set of active peers from which download can proceed
107-
stateDB ethdb.Database
108+
109+
stateDB ethdb.Database // Database to state sync into (and deduplicate via)
110+
stateBloom *trie.SyncBloom // Bloom filter for fast trie node existence checks
108111

109112
rttEstimate uint64 // Round trip time to target for download requests
110113
rttConfidence uint64 // Confidence in the estimated RTT (unit: millionths to allow atomic ops)
@@ -207,13 +210,13 @@ type BlockChain interface {
207210
}
208211

209212
// New creates a new downloader to fetch hashes and blocks from remote peers.
210-
func New(mode SyncMode, checkpoint uint64, stateDb ethdb.Database, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn) *Downloader {
213+
func New(checkpoint uint64, stateDb ethdb.Database, stateBloom *trie.SyncBloom, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn) *Downloader {
211214
if lightchain == nil {
212215
lightchain = chain
213216
}
214217
dl := &Downloader{
215-
mode: mode,
216218
stateDB: stateDb,
219+
stateBloom: stateBloom,
217220
mux: mux,
218221
checkpoint: checkpoint,
219222
queue: newQueue(),
@@ -255,13 +258,15 @@ func (d *Downloader) Progress() ethereum.SyncProgress {
255258
defer d.syncStatsLock.RUnlock()
256259

257260
current := uint64(0)
258-
switch d.mode {
259-
case FullSync:
261+
switch {
262+
case d.blockchain != nil && d.mode == FullSync:
260263
current = d.blockchain.CurrentBlock().NumberU64()
261-
case FastSync:
264+
case d.blockchain != nil && d.mode == FastSync:
262265
current = d.blockchain.CurrentFastBlock().NumberU64()
263-
case LightSync:
266+
case d.lightchain != nil:
264267
current = d.lightchain.CurrentHeader().Number.Uint64()
268+
default:
269+
log.Error("Unknown downloader chain/mode combo", "light", d.lightchain != nil, "full", d.blockchain != nil, "mode", d.mode)
265270
}
266271
return ethereum.SyncProgress{
267272
StartingBlock: d.syncStatsChainOrigin,
@@ -363,6 +368,12 @@ func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode
363368
if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
364369
log.Info("Block synchronisation started")
365370
}
371+
// If we are already full syncing, but have a fast-sync bloom filter laying
372+
// around, make sure it does't use memory any more. This is a special case
373+
// when the user attempts to fast sync a new empty network.
374+
if mode == FullSync && d.stateBloom != nil {
375+
d.stateBloom.Close()
376+
}
366377
// Reset the queue, peer set and wake channels to clean any internal leftover state
367378
d.queue.Reset()
368379
d.peers.Reset()
@@ -1662,13 +1673,24 @@ func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *state
16621673
func (d *Downloader) commitPivotBlock(result *fetchResult) error {
16631674
block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
16641675
log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
1676+
1677+
// Commit the pivot block as the new head, will require full sync from here on
16651678
if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil {
16661679
return err
16671680
}
16681681
if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
16691682
return err
16701683
}
16711684
atomic.StoreInt32(&d.committed, 1)
1685+
1686+
// If we had a bloom filter for the state sync, deallocate it now. Note, we only
1687+
// deallocate internally, but keep the empty wrapper. This ensures that if we do
1688+
// a rollback after committing the pivot and restarting fast sync, we don't end
1689+
// up using a nil bloom. Empty bloom is fine, it just returns that it does not
1690+
// have the info we need, so reach down to the database instead.
1691+
if d.stateBloom != nil {
1692+
d.stateBloom.Close()
1693+
}
16721694
return nil
16731695
}
16741696

‎eth/downloader/downloader_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func newTester() *downloadTester {
7575
tester.stateDb = rawdb.NewMemoryDatabase()
7676
tester.stateDb.Put(testGenesis.Root().Bytes(), []byte{0x00})
7777

78-
tester.downloader = New(FullSync, 0, tester.stateDb, new(event.TypeMux), tester, nil, tester.dropPeer)
78+
tester.downloader = New(0, tester.stateDb, trie.NewSyncBloom(1, tester.stateDb), new(event.TypeMux), tester, nil, tester.dropPeer)
7979
return tester
8080
}
8181

‎eth/downloader/statesync.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ type stateSyncStats struct {
5959

6060
// syncState starts downloading state with the given root hash.
6161
func (d *Downloader) syncState(root common.Hash) *stateSync {
62+
// Create the state sync
6263
s := newStateSync(d, root)
6364
select {
6465
case d.stateSyncStart <- s:
@@ -239,7 +240,7 @@ type stateTask struct {
239240
func newStateSync(d *Downloader, root common.Hash) *stateSync {
240241
return &stateSync{
241242
d: d,
242-
sched: state.NewStateSync(root, d.stateDB),
243+
sched: state.NewStateSync(root, d.stateDB, d.stateBloom),
243244
keccak: sha3.NewLegacyKeccak256(),
244245
tasks: make(map[common.Hash]*stateTask),
245246
deliver: make(chan *stateReq),

‎eth/handler.go‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import (
3939
"github.com/ethereum/go-ethereum/p2p/enode"
4040
"github.com/ethereum/go-ethereum/params"
4141
"github.com/ethereum/go-ethereum/rlp"
42+
"github.com/ethereum/go-ethereum/trie"
4243
)
4344

4445
const (
@@ -105,7 +106,7 @@ type ProtocolManager struct {
105106

106107
// NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
107108
// with the Ethereum network.
108-
func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, whitelist map[uint64]common.Hash) (*ProtocolManager, error) {
109+
func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, cacheLimit int, whitelist map[uint64]common.Hash) (*ProtocolManager, error) {
109110
// Create the protocol manager with the base fields
110111
manager := &ProtocolManager{
111112
networkID: networkID,
@@ -120,12 +121,8 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne
120121
txsyncCh: make(chan *txsync),
121122
quitSync: make(chan struct{}),
122123
}
123-
// Figure out whether to allow fast sync or not
124-
if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
125-
log.Warn("Blockchain not empty, fast sync disabled")
126-
mode = downloader.FullSync
127-
}
128-
if mode == downloader.FastSync {
124+
// If fast sync was requested and our database is empty, grant it
125+
if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() == 0 {
129126
manager.fastSync = uint32(1)
130127
}
131128
// If we have trusted checkpoints, enforce them on the chain
@@ -137,7 +134,8 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne
137134
manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
138135
for i, version := range ProtocolVersions {
139136
// Skip protocol version if incompatible with the mode of operation
140-
if mode == downloader.FastSync && version < eth63 {
137+
// TODO(karalabe): hard-drop eth/62 from the code base
138+
if atomic.LoadUint32(&manager.fastSync) == 1 && version < eth63 {
141139
continue
142140
}
143141
// Compatible; initialise the sub-protocol
@@ -171,9 +169,16 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne
171169
if len(manager.SubProtocols) == 0 {
172170
return nil, errIncompatibleConfig
173171
}
174-
// Construct the different synchronisation mechanisms
175-
manager.downloader = downloader.New(mode, manager.checkpointNumber, chaindb, manager.eventMux, blockchain, nil, manager.removePeer)
172+
// Construct the downloader (long sync) and its backing state bloom if fast
173+
// sync is requested. The downloader is responsible for deallocating the state
174+
// bloom when it's done.
175+
var stateBloom *trie.SyncBloom
176+
if atomic.LoadUint32(&manager.fastSync) == 1 {
177+
stateBloom = trie.NewSyncBloom(uint64(cacheLimit), chaindb)
178+
}
179+
manager.downloader = downloader.New(manager.checkpointNumber, chaindb, stateBloom, manager.eventMux, blockchain, nil, manager.removePeer)
176180

181+
// Construct the fetcher (short sync)
177182
validator := func(header *types.Header) error {
178183
return engine.VerifyHeader(blockchain, header, true)
179184
}

‎eth/handler_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpo
528528
if err != nil {
529529
t.Fatalf("failed to create new blockchain: %v", err)
530530
}
531-
pm, err := NewProtocolManager(config, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), ethash.NewFaker(), blockchain, db, nil)
531+
pm, err := NewProtocolManager(config, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), ethash.NewFaker(), blockchain, db, 1, nil)
532532
if err != nil {
533533
t.Fatalf("failed to start test protocol manager: %v", err)
534534
}
@@ -615,7 +615,7 @@ func testBroadcastBlock(t *testing.T, totalPeers, broadcastExpected int) {
615615
if err != nil {
616616
t.Fatalf("failed to create new blockchain: %v", err)
617617
}
618-
pm, err := NewProtocolManager(config, downloader.FullSync, DefaultConfig.NetworkId, evmux, new(testTxPool), pow, blockchain, db, nil)
618+
pm, err := NewProtocolManager(config, downloader.FullSync, DefaultConfig.NetworkId, evmux, new(testTxPool), pow, blockchain, db, 1, nil)
619619
if err != nil {
620620
t.Fatalf("failed to start test protocol manager: %v", err)
621621
}

0 commit comments

Comments
 (0)