Skip to content

Commit fecf214

Browse files
committed
core: fix a lock annoyance and potential deadlock
1 parent 5f341e5 commit fecf214

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

core/chain_manager.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,8 @@ func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error
376376
return nil
377377
}
378378

379+
// insert appends injects a block into the current chain block chain. Note, this
380+
// function assumes that the `mu` mutex is held!
379381
func (bc *ChainManager) insert(block *types.Block) {
380382
key := append(blockNumPre, block.Number().Bytes()...)
381383
bc.blockDb.Put(key, block.Hash().Bytes())
@@ -484,6 +486,8 @@ func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks [
484486
return
485487
}
486488

489+
// setTotalDifficulty updates the TD of the chain manager. Note, this function
490+
// assumes that the `mu` mutex is held!
487491
func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
488492
bc.td = new(big.Int).Set(td)
489493
}
@@ -540,9 +544,6 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
540544
self.wg.Add(1)
541545
defer self.wg.Done()
542546

543-
self.mu.Lock()
544-
defer self.mu.Unlock()
545-
546547
self.chainmu.Lock()
547548
defer self.chainmu.Unlock()
548549

@@ -625,7 +626,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
625626
cblock := self.currentBlock
626627
// Compare the TD of the last known block in the canonical chain to make sure it's greater.
627628
// At this point it's possible that a different chain (fork) becomes the new canonical chain.
628-
if block.Td.Cmp(self.td) > 0 {
629+
if block.Td.Cmp(self.Td()) > 0 {
629630
// chain fork
630631
if block.ParentHash() != cblock.Hash() {
631632
// during split we merge two different chains and create the new canonical chain
@@ -638,8 +639,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
638639
queueEvent.splitCount++
639640
}
640641

642+
self.mu.Lock()
641643
self.setTotalDifficulty(block.Td)
642644
self.insert(block)
645+
self.mu.Unlock()
643646

644647
jsonlogger.LogJson(&logger.EthChainNewHead{
645648
BlockHash: block.Hash().Hex(),
@@ -747,9 +750,11 @@ func (self *ChainManager) merge(oldBlock, newBlock *types.Block) error {
747750
}
748751

749752
// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
753+
self.mu.Lock()
750754
for _, block := range newChain {
751755
self.insert(block)
752756
}
757+
self.mu.Unlock()
753758

754759
return nil
755760
}

0 commit comments

Comments
 (0)