@@ -883,10 +883,10 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
883883
884884var lastWrite uint64
885885
886- // WriteBlockWithoutState writes only the block and its metadata to the database,
886+ // writeBlockWithoutState writes only the block and its metadata to the database,
887887// but does not write any state. This is used to construct competing side forks
888888// up to the point where they exceed the canonical total difficulty.
889- func (bc * BlockChain ) WriteBlockWithoutState (block * types.Block , td * big.Int ) (err error ) {
889+ func (bc * BlockChain ) writeBlockWithoutState (block * types.Block , td * big.Int ) (err error ) {
890890 bc .wg .Add (1 )
891891 defer bc .wg .Done ()
892892
@@ -898,6 +898,26 @@ func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (e
898898 return nil
899899}
900900
901+ // writeKnownBlock updates the head block flag with a known block
902+ // and introduces chain reorg if necessary.
903+ func (bc * BlockChain ) writeKnownBlock (block * types.Block ) error {
904+ bc .wg .Add (1 )
905+ defer bc .wg .Done ()
906+
907+ current := bc .CurrentBlock ()
908+ if block .ParentHash () != current .Hash () {
909+ if err := bc .reorg (current , block ); err != nil {
910+ return err
911+ }
912+ }
913+ // Write the positional metadata for transaction/receipt lookups.
914+ // Preimages here is empty, ignore it.
915+ rawdb .WriteTxLookupEntries (bc .db , block )
916+
917+ bc .insert (block )
918+ return nil
919+ }
920+
901921// WriteBlockWithState writes the block and all associated state to the database.
902922func (bc * BlockChain ) WriteBlockWithState (block * types.Block , receipts []* types.Receipt , state * state.StateDB ) (status WriteStatus , err error ) {
903923 bc .chainmu .Lock ()
@@ -1139,18 +1159,42 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
11391159 // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
11401160 // from the canonical chain, which has not been verified.
11411161 // Skip all known blocks that are behind us
1142- current := bc .CurrentBlock ().NumberU64 ()
1143- for block != nil && err == ErrKnownBlock && current >= block .NumberU64 () {
1162+ var (
1163+ current = bc .CurrentBlock ()
1164+ localTd = bc .GetTd (current .Hash (), current .NumberU64 ())
1165+ externTd = bc .GetTd (block .ParentHash (), block .NumberU64 ()- 1 ) // The first block can't be nil
1166+ )
1167+ for block != nil && err == ErrKnownBlock {
1168+ externTd = new (big.Int ).Add (externTd , block .Difficulty ())
1169+ if localTd .Cmp (externTd ) < 0 {
1170+ break
1171+ }
11441172 stats .ignored ++
11451173 block , err = it .next ()
11461174 }
1175+ // The remaining blocks are still known blocks, the only scenario here is:
1176+ // During the fast sync, the pivot point is already submitted but rollback
1177+ // happens. Then node resets the head full block to a lower height via `rollback`
1178+ // and leaves a few known blocks in the database.
1179+ //
1180+ // When node runs a fast sync again, it can re-import a batch of known blocks via
1181+ // `insertChain` while a part of them have higher total difficulty than current
1182+ // head full block(new pivot point).
1183+ for block != nil && err == ErrKnownBlock {
1184+ if err := bc .writeKnownBlock (block ); err != nil {
1185+ return it .index , nil , nil , err
1186+ }
1187+ lastCanon = block
1188+
1189+ block , err = it .next ()
1190+ }
11471191 // Falls through to the block import
11481192 }
11491193
11501194 switch {
11511195 // First block is pruned, insert as sidechain and reorg only if TD grows enough
11521196 case err == consensus .ErrPrunedAncestor :
1153- return bc .insertSidechain (block , it )
1197+ return bc .insertSideChain (block , it )
11541198
11551199 // First block is future, shove it (and all children) to the future queue (unknown ancestor)
11561200 case err == consensus .ErrFutureBlock || (err == consensus .ErrUnknownAncestor && bc .futureBlocks .Contains (it .first ().ParentHash ())):
@@ -1313,13 +1357,13 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
13131357 return it .index , events , coalescedLogs , err
13141358}
13151359
1316- // insertSidechain is called when an import batch hits upon a pruned ancestor
1360+ // insertSideChain is called when an import batch hits upon a pruned ancestor
13171361// error, which happens when a sidechain with a sufficiently old fork-block is
13181362// found.
13191363//
13201364// The method writes all (header-and-body-valid) blocks to disk, then tries to
13211365// switch over to the new chain if the TD exceeded the current chain.
1322- func (bc * BlockChain ) insertSidechain (block * types.Block , it * insertIterator ) (int , []interface {}, []* types.Log , error ) {
1366+ func (bc * BlockChain ) insertSideChain (block * types.Block , it * insertIterator ) (int , []interface {}, []* types.Log , error ) {
13231367 var (
13241368 externTd * big.Int
13251369 current = bc .CurrentBlock ()
@@ -1360,7 +1404,7 @@ func (bc *BlockChain) insertSidechain(block *types.Block, it *insertIterator) (i
13601404
13611405 if ! bc .HasBlock (block .Hash (), block .NumberU64 ()) {
13621406 start := time .Now ()
1363- if err := bc .WriteBlockWithoutState (block , externTd ); err != nil {
1407+ if err := bc .writeBlockWithoutState (block , externTd ); err != nil {
13641408 return it .index , nil , nil , err
13651409 }
13661410 log .Debug ("Injected sidechain block" , "number" , block .Number (), "hash" , block .Hash (),
@@ -1524,15 +1568,15 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
15241568 } else {
15251569 log .Error ("Impossible reorg, please file an issue" , "oldnum" , oldBlock .Number (), "oldhash" , oldBlock .Hash (), "newnum" , newBlock .Number (), "newhash" , newBlock .Hash ())
15261570 }
1527- // Insert the new chain, taking care of the proper incremental order
1528- for i := len (newChain ) - 1 ; i >= 0 ; i -- {
1571+ // Insert the new chain(except the head block(reverse order)),
1572+ // taking care of the proper incremental order.
1573+ for i := len (newChain ) - 1 ; i >= 1 ; i -- {
15291574 // Insert the block in the canonical way, re-writing history
15301575 bc .insert (newChain [i ])
15311576
1532- // Collect reborn logs due to chain reorg (except head block (reverse order))
1533- if i != 0 {
1534- collectLogs (newChain [i ].Hash (), false )
1535- }
1577+ // Collect reborn logs due to chain reorg
1578+ collectLogs (newChain [i ].Hash (), false )
1579+
15361580 // Write lookup entries for hash based transaction/receipt searches
15371581 rawdb .WriteTxLookupEntries (bc .db , newChain [i ])
15381582 addedTxs = append (addedTxs , newChain [i ].Transactions ()... )
0 commit comments