Skip to content

Commit a9d8dfc

Browse files
committed
core, eth: roll back uncertain headers in failed fast syncs
1 parent b97e34a commit a9d8dfc

6 files changed

Lines changed: 180 additions & 15 deletions

File tree

‎core/blockchain.go‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,21 @@ func (bc *BlockChain) SetHead(head uint64) {
245245
if bc.currentBlock == nil {
246246
bc.currentBlock = bc.genesisBlock
247247
}
248-
bc.insert(bc.currentBlock)
248+
if bc.currentHeader == nil {
249+
bc.currentHeader = bc.genesisBlock.Header()
250+
}
251+
if bc.currentFastBlock == nil {
252+
bc.currentFastBlock = bc.genesisBlock
253+
}
254+
if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil {
255+
glog.Fatalf("failed to reset head block hash: %v", err)
256+
}
257+
if err := WriteHeadHeaderHash(bc.chainDb, bc.currentHeader.Hash()); err != nil {
258+
glog.Fatalf("failed to reset head header hash: %v", err)
259+
}
260+
if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil {
261+
glog.Fatalf("failed to reset head fast block hash: %v", err)
262+
}
249263
bc.loadLastState()
250264
}
251265

@@ -790,6 +804,27 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int)
790804
return 0, nil
791805
}
792806

807+
// Rollback is designed to remove a chain of links from the database that aren't
808+
// certain enough to be valid.
809+
func (self *BlockChain) Rollback(chain []common.Hash) {
810+
for i := len(chain) - 1; i >= 0; i-- {
811+
hash := chain[i]
812+
813+
if self.currentHeader.Hash() == hash {
814+
self.currentHeader = self.GetHeader(self.currentHeader.ParentHash)
815+
WriteHeadHeaderHash(self.chainDb, self.currentHeader.Hash())
816+
}
817+
if self.currentFastBlock.Hash() == hash {
818+
self.currentFastBlock = self.GetBlock(self.currentFastBlock.ParentHash())
819+
WriteHeadFastBlockHash(self.chainDb, self.currentFastBlock.Hash())
820+
}
821+
if self.currentBlock.Hash() == hash {
822+
self.currentBlock = self.GetBlock(self.currentBlock.ParentHash())
823+
WriteHeadBlockHash(self.chainDb, self.currentBlock.Hash())
824+
}
825+
}
826+
}
827+
793828
// InsertReceiptChain attempts to complete an already existing header chain with
794829
// transaction and receipt data.
795830
func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {

‎core/blockchain_test.go‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -599,8 +599,8 @@ func testReorgBadHashes(t *testing.T, full bool) {
599599
t.Errorf("last block gasLimit mismatch: have: %x, want %x", ncm.GasLimit(), blocks[2].Header().GasLimit)
600600
}
601601
} else {
602-
if ncm.CurrentHeader().Hash() != genesis.Hash() {
603-
t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), genesis.Hash())
602+
if ncm.CurrentHeader().Hash() != headers[2].Hash() {
603+
t.Errorf("last header hash mismatch: have: %x, want %x", ncm.CurrentHeader().Hash(), headers[2].Hash())
604604
}
605605
}
606606
}
@@ -775,6 +775,11 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
775775
height := uint64(1024)
776776
blocks, receipts := GenerateChain(genesis, gendb, int(height), nil)
777777

778+
// Configure a subchain to roll back
779+
remove := []common.Hash{}
780+
for _, block := range blocks[height/2:] {
781+
remove = append(remove, block.Hash())
782+
}
778783
// Create a small assertion method to check the three heads
779784
assert := func(t *testing.T, kind string, chain *BlockChain, header uint64, fast uint64, block uint64) {
780785
if num := chain.CurrentBlock().NumberU64(); num != block {
@@ -798,6 +803,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
798803
t.Fatalf("failed to process block %d: %v", n, err)
799804
}
800805
assert(t, "archive", archive, height, height, height)
806+
archive.Rollback(remove)
807+
assert(t, "archive", archive, height/2, height/2, height/2)
801808

802809
// Import the chain as a non-archive node and ensure all pointers are updated
803810
fastDb, _ := ethdb.NewMemDatabase()
@@ -816,6 +823,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
816823
t.Fatalf("failed to insert receipt %d: %v", n, err)
817824
}
818825
assert(t, "fast", fast, height, height, 0)
826+
fast.Rollback(remove)
827+
assert(t, "fast", fast, height/2, height/2, 0)
819828

820829
// Import the chain as a light node and ensure all pointers are updated
821830
lightDb, _ := ethdb.NewMemDatabase()
@@ -827,6 +836,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
827836
t.Fatalf("failed to insert header %d: %v", n, err)
828837
}
829838
assert(t, "light", light, height, 0, 0)
839+
light.Rollback(remove)
840+
assert(t, "light", light, height/2, 0, 0)
830841
}
831842

832843
// Tests that chain reorganizations handle transaction removals and reinsertions.

‎eth/downloader/downloader.go‎

Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ var (
5959
maxQueuedStates = 256 * 1024 // [eth/63] Maximum number of state requests to queue (DOS protection)
6060
maxResultsProcess = 256 // Number of download results to import at once into the chain
6161

62-
headerCheckFrequency = 64 // Verification frequency of the downloaded headers during fast sync
63-
minCheckedHeaders = 1024 // Number of headers to verify fully when approaching the chain head
62+
headerCheckFrequency = 100 // Verification frequency of the downloaded headers during fast sync
63+
minCheckedHeaders = 2048 // Number of headers to verify fully when approaching the chain head
6464
minFullBlocks = 1024 // Number of blocks to retrieve fully even in fast sync
6565
)
6666

@@ -117,6 +117,7 @@ type Downloader struct {
117117
insertHeaders headerChainInsertFn // Injects a batch of headers into the chain
118118
insertBlocks blockChainInsertFn // Injects a batch of blocks into the chain
119119
insertReceipts receiptChainInsertFn // Injects a batch of blocks and their receipts into the chain
120+
rollback chainRollbackFn // Removes a batch of recently added chain links
120121
dropPeer peerDropFn // Drops a peer for misbehaving
121122

122123
// Status
@@ -152,7 +153,7 @@ type Downloader struct {
152153
func New(mode SyncMode, stateDb ethdb.Database, mux *event.TypeMux, hasHeader headerCheckFn, hasBlock blockCheckFn, getHeader headerRetrievalFn,
153154
getBlock blockRetrievalFn, headHeader headHeaderRetrievalFn, headBlock headBlockRetrievalFn, headFastBlock headFastBlockRetrievalFn,
154155
commitHeadBlock headBlockCommitterFn, getTd tdRetrievalFn, insertHeaders headerChainInsertFn, insertBlocks blockChainInsertFn,
155-
insertReceipts receiptChainInsertFn, dropPeer peerDropFn) *Downloader {
156+
insertReceipts receiptChainInsertFn, rollback chainRollbackFn, dropPeer peerDropFn) *Downloader {
156157

157158
return &Downloader{
158159
mode: mode,
@@ -171,6 +172,7 @@ func New(mode SyncMode, stateDb ethdb.Database, mux *event.TypeMux, hasHeader he
171172
insertHeaders: insertHeaders,
172173
insertBlocks: insertBlocks,
173174
insertReceipts: insertReceipts,
175+
rollback: rollback,
174176
dropPeer: dropPeer,
175177
newPeerCh: make(chan *peer, 1),
176178
hashCh: make(chan dataPack, 1),
@@ -383,7 +385,7 @@ func (d *Downloader) syncWithPeer(p *peer, hash common.Hash, td *big.Int) (err e
383385
d.syncStatsChainHeight = latest
384386
d.syncStatsLock.Unlock()
385387

386-
// Initiate the sync using a concurrent header and content retrieval algorithm
388+
// Initiate the sync using a concurrent header and content retrieval algorithm
387389
pivot := uint64(0)
388390
if latest > uint64(minFullBlocks) {
389391
pivot = latest - uint64(minFullBlocks)
@@ -394,10 +396,10 @@ func (d *Downloader) syncWithPeer(p *peer, hash common.Hash, td *big.Int) (err e
394396
d.syncInitHook(origin, latest)
395397
}
396398
errc := make(chan error, 4)
397-
go func() { errc <- d.fetchHeaders(p, td, origin+1) }() // Headers are always retrieved
398-
go func() { errc <- d.fetchBodies(origin + 1) }() // Bodies are retrieved during normal and fast sync
399-
go func() { errc <- d.fetchReceipts(origin + 1) }() // Receipts are retrieved during fast sync
400-
go func() { errc <- d.fetchNodeData() }() // Node state data is retrieved during fast sync
399+
go func() { errc <- d.fetchHeaders(p, td, origin+1, latest) }() // Headers are always retrieved
400+
go func() { errc <- d.fetchBodies(origin + 1) }() // Bodies are retrieved during normal and fast sync
401+
go func() { errc <- d.fetchReceipts(origin + 1) }() // Receipts are retrieved during fast sync
402+
go func() { errc <- d.fetchNodeData() }() // Node state data is retrieved during fast sync
401403

402404
// If any fetcher fails, cancel the others
403405
var fail error
@@ -1049,10 +1051,28 @@ func (d *Downloader) findAncestor(p *peer) (uint64, error) {
10491051
//
10501052
// The queue parameter can be used to switch between queuing headers for block
10511053
// body download too, or directly import as pure header chains.
1052-
func (d *Downloader) fetchHeaders(p *peer, td *big.Int, from uint64) error {
1054+
func (d *Downloader) fetchHeaders(p *peer, td *big.Int, from, latest uint64) error {
10531055
glog.V(logger.Debug).Infof("%v: downloading headers from #%d", p, from)
10541056
defer glog.V(logger.Debug).Infof("%v: header download terminated", p)
10551057

1058+
// Keep a count of uncertain headers to roll back
1059+
rollback := []*types.Header{}
1060+
defer func() {
1061+
if len(rollback) > 0 {
1062+
hashes := make([]common.Hash, len(rollback))
1063+
for i, header := range rollback {
1064+
hashes[i] = header.Hash()
1065+
}
1066+
d.rollback(hashes)
1067+
}
1068+
}()
1069+
// Calculate the pivoting point for switching from fast to slow sync
1070+
pivot := uint64(0)
1071+
if d.mode == FastSync && latest > uint64(minFullBlocks) {
1072+
pivot = latest - uint64(minFullBlocks)
1073+
} else if d.mode == LightSync {
1074+
pivot = latest
1075+
}
10561076
// Create a timeout timer, and the associated hash fetcher
10571077
request := time.Now() // time of the last fetch request
10581078
timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
@@ -1124,10 +1144,30 @@ func (d *Downloader) fetchHeaders(p *peer, td *big.Int, from uint64) error {
11241144
glog.V(logger.Detail).Infof("%v: schedule %d headers from #%d", p, len(headers), from)
11251145

11261146
if d.mode == FastSync || d.mode == LightSync {
1127-
if n, err := d.insertHeaders(headers, headerCheckFrequency); err != nil {
1147+
// Collect the yet unknown headers to mark them as uncertain
1148+
unknown := make([]*types.Header, 0, len(headers))
1149+
for _, header := range headers {
1150+
if !d.hasHeader(header.Hash()) {
1151+
unknown = append(unknown, header)
1152+
}
1153+
}
1154+
// If we're importing pure headers, verify based on their recentness
1155+
frequency := headerCheckFrequency
1156+
if headers[len(headers)-1].Number.Uint64()+uint64(minCheckedHeaders) > pivot {
1157+
frequency = 1
1158+
}
1159+
if n, err := d.insertHeaders(headers, frequency); err != nil {
11281160
glog.V(logger.Debug).Infof("%v: invalid header #%d [%x…]: %v", p, headers[n].Number, headers[n].Hash().Bytes()[:4], err)
11291161
return errInvalidChain
11301162
}
1163+
// All verifications passed, store newly found uncertain headers
1164+
rollback = append(rollback, unknown...)
1165+
if len(rollback) > minCheckedHeaders {
1166+
rollback = append(rollback[:0], rollback[len(rollback)-minCheckedHeaders:]...)
1167+
}
1168+
if headers[len(headers)-1].Number.Uint64() >= pivot {
1169+
rollback = rollback[:0]
1170+
}
11311171
}
11321172
if d.mode == FullSync || d.mode == FastSync {
11331173
inserts := d.queue.Schedule(headers, from)

‎eth/downloader/downloader_test.go‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ func newTester(mode SyncMode) *downloadTester {
152152
tester.stateDb, _ = ethdb.NewMemDatabase()
153153
tester.downloader = New(mode, tester.stateDb, new(event.TypeMux), tester.hasHeader, tester.hasBlock, tester.getHeader,
154154
tester.getBlock, tester.headHeader, tester.headBlock, tester.headFastBlock, tester.commitHeadBlock, tester.getTd,
155-
tester.insertHeaders, tester.insertBlocks, tester.insertReceipts, tester.dropPeer)
155+
tester.insertHeaders, tester.insertBlocks, tester.insertReceipts, tester.rollback, tester.dropPeer)
156156

157157
return tester
158158
}
@@ -272,6 +272,16 @@ func (dl *downloadTester) insertHeaders(headers []*types.Header, checkFreq int)
272272
dl.lock.Lock()
273273
defer dl.lock.Unlock()
274274

275+
// Do a quick check, as the blockchain.InsertHeaderChain doesn't insert anthing in case of errors
276+
if _, ok := dl.ownHeaders[headers[0].ParentHash]; !ok {
277+
return 0, errors.New("unknown parent")
278+
}
279+
for i := 1; i < len(headers); i++ {
280+
if headers[i].ParentHash != headers[i-1].Hash() {
281+
return i, errors.New("unknown parent")
282+
}
283+
}
284+
// Do a full insert if pre-checks passed
275285
for i, header := range headers {
276286
if _, ok := dl.ownHeaders[header.Hash()]; ok {
277287
continue
@@ -322,6 +332,22 @@ func (dl *downloadTester) insertReceipts(blocks types.Blocks, receipts []types.R
322332
return len(blocks), nil
323333
}
324334

335+
// rollback removes some recently added elements from the chain.
336+
func (dl *downloadTester) rollback(hashes []common.Hash) {
337+
dl.lock.Lock()
338+
defer dl.lock.Unlock()
339+
340+
for i := len(hashes) - 1; i >= 0; i-- {
341+
if dl.ownHashes[len(dl.ownHashes)-1] == hashes[i] {
342+
dl.ownHashes = dl.ownHashes[:len(dl.ownHashes)-1]
343+
}
344+
delete(dl.ownChainTd, hashes[i])
345+
delete(dl.ownHeaders, hashes[i])
346+
delete(dl.ownReceipts, hashes[i])
347+
delete(dl.ownBlocks, hashes[i])
348+
}
349+
}
350+
325351
// newPeer registers a new block download source into the downloader.
326352
func (dl *downloadTester) newPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*types.Header, blocks map[common.Hash]*types.Block, receipts map[common.Hash]types.Receipts) error {
327353
return dl.newSlowPeer(id, version, hashes, headers, blocks, receipts, 0)
@@ -1031,6 +1057,56 @@ func testShiftedHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
10311057
assertOwnChain(t, tester, targetBlocks+1)
10321058
}
10331059

1060+
// Tests that upon detecting an invalid header, the recent ones are rolled back
1061+
func TestInvalidHeaderRollback63Fast(t *testing.T) { testInvalidHeaderRollback(t, 63, FastSync) }
1062+
func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) }
1063+
func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }
1064+
1065+
func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
1066+
// Create a small enough block chain to download
1067+
targetBlocks := 3*minCheckedHeaders + minFullBlocks
1068+
hashes, headers, blocks, receipts := makeChain(targetBlocks, 0, genesis, nil)
1069+
1070+
tester := newTester(mode)
1071+
1072+
// Attempt to sync with an attacker that feeds junk during the fast sync phase
1073+
tester.newPeer("fast-attack", protocol, hashes, headers, blocks, receipts)
1074+
missing := minCheckedHeaders + MaxHeaderFetch + 1
1075+
delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing])
1076+
1077+
if err := tester.sync("fast-attack", nil); err == nil {
1078+
t.Fatalf("succeeded fast attacker synchronisation")
1079+
}
1080+
if head := tester.headHeader().Number.Int64(); int(head) > MaxHeaderFetch {
1081+
t.Fatalf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
1082+
}
1083+
// Attempt to sync with an attacker that feeds junk during the block import phase
1084+
tester.newPeer("block-attack", protocol, hashes, headers, blocks, receipts)
1085+
missing = 3*minCheckedHeaders + MaxHeaderFetch + 1
1086+
delete(tester.peerHeaders["block-attack"], hashes[len(hashes)-missing])
1087+
1088+
if err := tester.sync("block-attack", nil); err == nil {
1089+
t.Fatalf("succeeded block attacker synchronisation")
1090+
}
1091+
if mode == FastSync {
1092+
// Fast sync should not discard anything below the verified pivot point
1093+
if head := tester.headHeader().Number.Int64(); int(head) < 3*minCheckedHeaders {
1094+
t.Fatalf("rollback head mismatch: have %v, want at least %v", head, 3*minCheckedHeaders)
1095+
}
1096+
} else if mode == LightSync {
1097+
// Light sync should still discard data as before
1098+
if head := tester.headHeader().Number.Int64(); int(head) > 3*minCheckedHeaders {
1099+
t.Fatalf("rollback head mismatch: have %v, want at most %v", head, 3*minCheckedHeaders)
1100+
}
1101+
}
1102+
// Synchronise with the valid peer and make sure sync succeeds
1103+
tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
1104+
if err := tester.sync("valid", nil); err != nil {
1105+
t.Fatalf("failed to synchronise blocks: %v", err)
1106+
}
1107+
assertOwnChain(t, tester, targetBlocks+1)
1108+
}
1109+
10341110
// Tests that if a peer sends an invalid block piece (body or receipt) for a
10351111
// requested block, it gets dropped immediately by the downloader.
10361112
func TestInvalidContentAttack62(t *testing.T) { testInvalidContentAttack(t, 62, FullSync) }

‎eth/downloader/types.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ type blockChainInsertFn func(types.Blocks) (int, error)
6060
// receiptChainInsertFn is a callback type to insert a batch of receipts into the local chain.
6161
type receiptChainInsertFn func(types.Blocks, []types.Receipts) (int, error)
6262

63+
// chainRollbackFn is a callback type to remove a few recently added elements from the local chain.
64+
type chainRollbackFn func([]common.Hash)
65+
6366
// peerDropFn is a callback type for dropping a peer detected as malicious.
6467
type peerDropFn func(id string)
6568

‎eth/handler.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ func NewProtocolManager(mode Mode, networkId int, mux *event.TypeMux, txpool txP
131131
}
132132
manager.downloader = downloader.New(syncMode, chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlock, blockchain.GetHeader,
133133
blockchain.GetBlock, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead,
134-
blockchain.GetTd, blockchain.InsertHeaderChain, blockchain.InsertChain, blockchain.InsertReceiptChain, manager.removePeer)
134+
blockchain.GetTd, blockchain.InsertHeaderChain, blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback, manager.removePeer)
135135

136136
validator := func(block *types.Block, parent *types.Block) error {
137137
return core.ValidateHeader(pow, block.Header(), parent.Header(), true, false)

0 commit comments

Comments
 (0)