@@ -601,7 +601,7 @@ func (self *BlockChain) writeHeader(header *types.Header) error {
601601}
602602
603603// InsertHeaderChain will attempt to insert the given header chain in to the
604- // local chain, possibly creating a dork . If an error is returned, it will
604+ // local chain, possibly creating a fork . If an error is returned, it will
605605// return the index number of the failing header as well an error describing
606606// what went wrong.
607607//
@@ -686,37 +686,31 @@ func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err
686686 }
687687 td := new (big.Int ).Add (block .Difficulty (), ptd )
688688
689- self . mu . RLock ()
690- cblock := self .currentBlock
691- self .mu .RUnlock ()
689+ // Make sure no inconsistent state is leaked during insertion
690+ self .mu . Lock ()
691+ defer self .mu .Unlock ()
692692
693- // Compare the TD of the last known block in the canonical chain to make sure it's greater.
694- // At this point it's possible that a different chain (fork) becomes the new canonical chain.
693+ // If the total difficulty is higher than our known, add it to the canonical chain
695694 if td .Cmp (self .GetTd (self .currentBlock .Hash ())) > 0 {
696- // chain fork
697- if block .ParentHash () != cblock .Hash () {
698- // during split we merge two different chains and create the new canonical chain
699- err := self .reorg (cblock , block )
700- if err != nil {
695+ // Reorganize the chain if the parent is not the head block
696+ if block .ParentHash () != self .currentBlock .Hash () {
697+ if err := self .reorg (self .currentBlock , block ); err != nil {
701698 return NonStatTy , err
702699 }
703700 }
704- status = CanonStatTy
705-
706- self .mu .Lock ()
701+ // Insert the block as the new head of the chain
707702 self .insert (block )
708- self . mu . Unlock ()
703+ status = CanonStatTy
709704 } else {
710705 status = SideStatTy
711706 }
712-
707+ // Irrelevant of the canonical status, write the block itself to the database
713708 if err := WriteTd (self .chainDb , block .Hash (), td ); err != nil {
714709 glog .Fatalf ("failed to write block total difficulty: %v" , err )
715710 }
716711 if err := WriteBlock (self .chainDb , block ); err != nil {
717712 glog .Fatalf ("filed to write block contents: %v" , err )
718713 }
719- // Delete from future blocks
720714 self .futureBlocks .Remove (block .Hash ())
721715
722716 return
@@ -860,9 +854,6 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
860854// to be part of the new canonical chain and accumulates potential missing transactions and post an
861855// event about them
862856func (self * BlockChain ) reorg (oldBlock , newBlock * types.Block ) error {
863- self .mu .Lock ()
864- defer self .mu .Unlock ()
865-
866857 var (
867858 newChain types.Blocks
868859 commonBlock * types.Block
0 commit comments