@@ -407,6 +407,11 @@ func (bc *BlockChain) SetHead(head uint64) error {
407407 }
408408 }
409409 rawdb .WriteHeadBlockHash (db , newHeadBlock .Hash ())
410+
411+ // Degrade the chain markers if they are explicitly reverted.
412+ // In theory we should update all in-memory markers in the
413+ // last step, however the direction of SetHead is from high
414+ // to low, so it's safe the update in-memory markers directly.
410415 bc .currentBlock .Store (newHeadBlock )
411416 headBlockGauge .Update (int64 (newHeadBlock .NumberU64 ()))
412417 }
@@ -419,6 +424,11 @@ func (bc *BlockChain) SetHead(head uint64) error {
419424 newHeadFastBlock = bc .genesisBlock
420425 }
421426 rawdb .WriteHeadFastBlockHash (db , newHeadFastBlock .Hash ())
427+
428+ // Degrade the chain markers if they are explicitly reverted.
429+ // In theory we should update all in-memory markers in the
430+ // last step, however the direction of SetHead is from high
431+ // to low, so it's safe the update in-memory markers directly.
422432 bc .currentFastBlock .Store (newHeadFastBlock )
423433 headFastBlockGauge .Update (int64 (newHeadFastBlock .NumberU64 ()))
424434 }
@@ -538,21 +548,22 @@ func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
538548 defer bc .chainmu .Unlock ()
539549
540550 // Prepare the genesis block and reinitialise the chain
541- if err := bc .hc .WriteTd (genesis .Hash (), genesis .NumberU64 (), genesis .Difficulty ()); err != nil {
542- log .Crit ("Failed to write genesis block TD" , "err" , err )
551+ batch := bc .db .NewBatch ()
552+ rawdb .WriteTd (batch , genesis .Hash (), genesis .NumberU64 (), genesis .Difficulty ())
553+ rawdb .WriteBlock (batch , genesis )
554+ if err := batch .Write (); err != nil {
555+ log .Crit ("Failed to write genesis block" , "err" , err )
543556 }
544- rawdb . WriteBlock ( bc .db , genesis )
557+ bc .writeHeadBlock ( genesis )
545558
559+ // Last update all in-memory chain markers
546560 bc .genesisBlock = genesis
547- bc .insert (bc .genesisBlock )
548561 bc .currentBlock .Store (bc .genesisBlock )
549562 headBlockGauge .Update (int64 (bc .genesisBlock .NumberU64 ()))
550-
551563 bc .hc .SetGenesis (bc .genesisBlock .Header ())
552564 bc .hc .SetCurrentHeader (bc .genesisBlock .Header ())
553565 bc .currentFastBlock .Store (bc .genesisBlock )
554566 headFastBlockGauge .Update (int64 (bc .genesisBlock .NumberU64 ()))
555-
556567 return nil
557568}
558569
@@ -610,31 +621,39 @@ func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
610621 return nil
611622}
612623
613- // insert injects a new head block into the current block chain. This method
624+ // writeHeadBlock injects a new head block into the current block chain. This method
614625// assumes that the block is indeed a true head. It will also reset the head
615626// header and the head fast sync block to this very same block if they are older
616627// or if they are on a different side chain.
617628//
618629// Note, this function assumes that the `mu` mutex is held!
619- func (bc * BlockChain ) insert (block * types.Block ) {
630+ func (bc * BlockChain ) writeHeadBlock (block * types.Block ) {
620631 // If the block is on a side chain or an unknown one, force other heads onto it too
621632 updateHeads := rawdb .ReadCanonicalHash (bc .db , block .NumberU64 ()) != block .Hash ()
622633
623634 // Add the block to the canonical chain number scheme and mark as the head
624- rawdb .WriteCanonicalHash (bc .db , block .Hash (), block .NumberU64 ())
625- rawdb .WriteHeadBlockHash (bc .db , block .Hash ())
626-
627- bc .currentBlock .Store (block )
628- headBlockGauge .Update (int64 (block .NumberU64 ()))
635+ batch := bc .db .NewBatch ()
636+ rawdb .WriteCanonicalHash (batch , block .Hash (), block .NumberU64 ())
637+ rawdb .WriteTxLookupEntries (batch , block )
638+ rawdb .WriteHeadBlockHash (batch , block .Hash ())
629639
630640 // If the block is better than our head or is on a different chain, force update heads
641+ if updateHeads {
642+ rawdb .WriteHeadHeaderHash (batch , block .Hash ())
643+ rawdb .WriteHeadFastBlockHash (batch , block .Hash ())
644+ }
645+ // Flush the whole batch into the disk, exit the node if failed
646+ if err := batch .Write (); err != nil {
647+ log .Crit ("Failed to update chain indexes and markers" , "err" , err )
648+ }
649+ // Update all in-memory chain markers in the last step
631650 if updateHeads {
632651 bc .hc .SetCurrentHeader (block .Header ())
633- rawdb .WriteHeadFastBlockHash (bc .db , block .Hash ())
634-
635652 bc .currentFastBlock .Store (block )
636653 headFastBlockGauge .Update (int64 (block .NumberU64 ()))
637654 }
655+ bc .currentBlock .Store (block )
656+ headBlockGauge .Update (int64 (block .NumberU64 ()))
638657}
639658
640659// Genesis retrieves the chain's genesis block.
@@ -881,26 +900,36 @@ func (bc *BlockChain) Rollback(chain []common.Hash) {
881900 bc .chainmu .Lock ()
882901 defer bc .chainmu .Unlock ()
883902
903+ batch := bc .db .NewBatch ()
884904 for i := len (chain ) - 1 ; i >= 0 ; i -- {
885905 hash := chain [i ]
886906
907+ // Degrade the chain markers if they are explicitly reverted.
908+ // In theory we should update all in-memory markers in the
909+ // last step, however the direction of rollback is from high
910+ // to low, so it's safe the update in-memory markers directly.
887911 currentHeader := bc .hc .CurrentHeader ()
888912 if currentHeader .Hash () == hash {
889- bc .hc .SetCurrentHeader (bc .GetHeader (currentHeader .ParentHash , currentHeader .Number .Uint64 ()- 1 ))
913+ newHeadHeader := bc .GetHeader (currentHeader .ParentHash , currentHeader .Number .Uint64 ()- 1 )
914+ rawdb .WriteHeadHeaderHash (batch , currentHeader .ParentHash )
915+ bc .hc .SetCurrentHeader (newHeadHeader )
890916 }
891917 if currentFastBlock := bc .CurrentFastBlock (); currentFastBlock .Hash () == hash {
892918 newFastBlock := bc .GetBlock (currentFastBlock .ParentHash (), currentFastBlock .NumberU64 ()- 1 )
893- rawdb .WriteHeadFastBlockHash (bc . db , newFastBlock . Hash ())
919+ rawdb .WriteHeadFastBlockHash (batch , currentFastBlock . ParentHash ())
894920 bc .currentFastBlock .Store (newFastBlock )
895921 headFastBlockGauge .Update (int64 (newFastBlock .NumberU64 ()))
896922 }
897923 if currentBlock := bc .CurrentBlock (); currentBlock .Hash () == hash {
898924 newBlock := bc .GetBlock (currentBlock .ParentHash (), currentBlock .NumberU64 ()- 1 )
899- rawdb .WriteHeadBlockHash (bc . db , newBlock . Hash ())
925+ rawdb .WriteHeadBlockHash (batch , currentBlock . ParentHash ())
900926 bc .currentBlock .Store (newBlock )
901927 headBlockGauge .Update (int64 (newBlock .NumberU64 ()))
902928 }
903929 }
930+ if err := batch .Write (); err != nil {
931+ log .Crit ("Failed to rollback chain markers" , "err" , err )
932+ }
904933 // Truncate ancient data which exceeds the current header.
905934 //
906935 // Notably, it can happen that system crashes without truncating the ancient data
@@ -1063,7 +1092,6 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
10631092 }
10641093 // Don't collect too much in-memory, write it out every 100K blocks
10651094 if len (deleted ) > 100000 {
1066-
10671095 // Sync the ancient store explicitly to ensure all data has been flushed to disk.
10681096 if err := bc .db .Sync (); err != nil {
10691097 return 0 , err
@@ -1172,15 +1200,21 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
11721200 rawdb .WriteReceipts (batch , block .Hash (), block .NumberU64 (), receiptChain [i ])
11731201 rawdb .WriteTxLookupEntries (batch , block )
11741202
1175- stats .processed ++
1203+ // Write everything belongs to the blocks into the database. So that
1204+ // we can ensure all components of body is completed(body, receipts,
1205+ // tx indexes)
11761206 if batch .ValueSize () >= ethdb .IdealBatchSize {
11771207 if err := batch .Write (); err != nil {
11781208 return 0 , err
11791209 }
11801210 size += batch .ValueSize ()
11811211 batch .Reset ()
11821212 }
1213+ stats .processed ++
11831214 }
1215+ // Write everything belongs to the blocks into the database. So that
1216+ // we can ensure all components of body is completed(body, receipts,
1217+ // tx indexes)
11841218 if batch .ValueSize () > 0 {
11851219 size += batch .ValueSize ()
11861220 if err := batch .Write (); err != nil {
@@ -1231,11 +1265,12 @@ func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (e
12311265 bc .wg .Add (1 )
12321266 defer bc .wg .Done ()
12331267
1234- if err := bc .hc .WriteTd (block .Hash (), block .NumberU64 (), td ); err != nil {
1235- return err
1268+ batch := bc .db .NewBatch ()
1269+ rawdb .WriteTd (batch , block .Hash (), block .NumberU64 (), td )
1270+ rawdb .WriteBlock (batch , block )
1271+ if err := batch .Write (); err != nil {
1272+ log .Crit ("Failed to write block into disk" , "err" , err )
12361273 }
1237- rawdb .WriteBlock (bc .db , block )
1238-
12391274 return nil
12401275}
12411276
@@ -1251,11 +1286,7 @@ func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
12511286 return err
12521287 }
12531288 }
1254- // Write the positional metadata for transaction/receipt lookups.
1255- // Preimages here is empty, ignore it.
1256- rawdb .WriteTxLookupEntries (bc .db , block )
1257-
1258- bc .insert (block )
1289+ bc .writeHeadBlock (block )
12591290 return nil
12601291}
12611292
@@ -1283,12 +1314,19 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
12831314 localTd := bc .GetTd (currentBlock .Hash (), currentBlock .NumberU64 ())
12841315 externTd := new (big.Int ).Add (block .Difficulty (), ptd )
12851316
1286- // Irrelevant of the canonical status, write the block itself to the database
1287- if err := bc .hc .WriteTd (block .Hash (), block .NumberU64 (), externTd ); err != nil {
1288- return NonStatTy , err
1289- }
1290- rawdb .WriteBlock (bc .db , block )
1291-
1317+ // Irrelevant of the canonical status, write the block itself to the database.
1318+ //
1319+ // Note all the components of block(td, hash->number map, header, body, receipts)
1320+ // should be written atomically. BlockBatch is used for containing all components.
1321+ blockBatch := bc .db .NewBatch ()
1322+ rawdb .WriteTd (blockBatch , block .Hash (), block .NumberU64 (), externTd )
1323+ rawdb .WriteBlock (blockBatch , block )
1324+ rawdb .WriteReceipts (blockBatch , block .Hash (), block .NumberU64 (), receipts )
1325+ rawdb .WritePreimages (blockBatch , state .Preimages ())
1326+ if err := blockBatch .Write (); err != nil {
1327+ log .Crit ("Failed to write block into disk" , "err" , err )
1328+ }
1329+ // Commit all cached state changes into underlying memory database.
12921330 root , err := state .Commit (bc .chainConfig .IsEIP158 (block .Number ()))
12931331 if err != nil {
12941332 return NonStatTy , err
@@ -1347,11 +1385,6 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
13471385 }
13481386 }
13491387 }
1350-
1351- // Write other block data using a batch.
1352- batch := bc .db .NewBatch ()
1353- rawdb .WriteReceipts (batch , block .Hash (), block .NumberU64 (), receipts )
1354-
13551388 // If the total difficulty is higher than our known, add it to the canonical chain
13561389 // Second clause in the if statement reduces the vulnerability to selfish mining.
13571390 // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
@@ -1377,21 +1410,13 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
13771410 return NonStatTy , err
13781411 }
13791412 }
1380- // Write the positional metadata for transaction/receipt lookups and preimages
1381- rawdb .WriteTxLookupEntries (batch , block )
1382- rawdb .WritePreimages (batch , state .Preimages ())
1383-
13841413 status = CanonStatTy
13851414 } else {
13861415 status = SideStatTy
13871416 }
1388- if err := batch .Write (); err != nil {
1389- return NonStatTy , err
1390- }
1391-
13921417 // Set new head.
13931418 if status == CanonStatTy {
1394- bc .insert (block )
1419+ bc .writeHeadBlock (block )
13951420 }
13961421 bc .futureBlocks .Remove (block .Hash ())
13971422
@@ -1991,20 +2016,19 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
19912016 // taking care of the proper incremental order.
19922017 for i := len (newChain ) - 1 ; i >= 1 ; i -- {
19932018 // Insert the block in the canonical way, re-writing history
1994- bc .insert (newChain [i ])
2019+ bc .writeHeadBlock (newChain [i ])
19952020
19962021 // Collect reborn logs due to chain reorg
19972022 collectLogs (newChain [i ].Hash (), false )
19982023
1999- // Write lookup entries for hash based transaction/receipt searches
2000- rawdb .WriteTxLookupEntries (bc .db , newChain [i ])
2024+ // Collect the new added transactions.
20012025 addedTxs = append (addedTxs , newChain [i ].Transactions ()... )
20022026 }
2003- // When transactions get deleted from the database, the receipts that were
2004- // created in the fork must also be deleted
2005- batch := bc .db .NewBatch ()
2027+ // Delete useless indexes right now which includes the non-canonical
2028+ // transaction indexes, canonical chain indexes which above the head.
2029+ indexesBatch := bc .db .NewBatch ()
20062030 for _ , tx := range types .TxDifference (deletedTxs , addedTxs ) {
2007- rawdb .DeleteTxLookupEntry (batch , tx .Hash ())
2031+ rawdb .DeleteTxLookupEntry (indexesBatch , tx .Hash ())
20082032 }
20092033 // Delete any canonical number assignments above the new head
20102034 number := bc .CurrentBlock ().NumberU64 ()
@@ -2013,9 +2037,11 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
20132037 if hash == (common.Hash {}) {
20142038 break
20152039 }
2016- rawdb .DeleteCanonicalHash (batch , i )
2040+ rawdb .DeleteCanonicalHash (indexesBatch , i )
2041+ }
2042+ if err := indexesBatch .Write (); err != nil {
2043+ log .Crit ("Failed to delete useless indexes" , "err" , err )
20172044 }
2018- batch .Write ()
20192045 // If any logs need to be fired, do it now. In theory we could avoid creating
20202046 // this goroutine if there are no events to fire, but realistcally that only
20212047 // ever happens if we're reorging empty blocks, which will only happen on idle
0 commit comments