@@ -376,6 +376,8 @@ func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error
376
376
return nil
377
377
}
378
378
379
+ // insert appends injects a block into the current chain block chain. Note, this
380
+ // function assumes that the `mu` mutex is held!
379
381
func (bc * ChainManager ) insert (block * types.Block ) {
380
382
key := append (blockNumPre , block .Number ().Bytes ()... )
381
383
bc .blockDb .Put (key , block .Hash ().Bytes ())
@@ -484,6 +486,8 @@ func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks [
484
486
return
485
487
}
486
488
489
+ // setTotalDifficulty updates the TD of the chain manager. Note, this function
490
+ // assumes that the `mu` mutex is held!
487
491
func (bc * ChainManager ) setTotalDifficulty (td * big.Int ) {
488
492
bc .td = new (big.Int ).Set (td )
489
493
}
@@ -540,9 +544,6 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
540
544
self .wg .Add (1 )
541
545
defer self .wg .Done ()
542
546
543
- self .mu .Lock ()
544
- defer self .mu .Unlock ()
545
-
546
547
self .chainmu .Lock ()
547
548
defer self .chainmu .Unlock ()
548
549
@@ -625,7 +626,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
625
626
cblock := self .currentBlock
626
627
// Compare the TD of the last known block in the canonical chain to make sure it's greater.
627
628
// 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 {
629
630
// chain fork
630
631
if block .ParentHash () != cblock .Hash () {
631
632
// 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) {
638
639
queueEvent .splitCount ++
639
640
}
640
641
642
+ self .mu .Lock ()
641
643
self .setTotalDifficulty (block .Td )
642
644
self .insert (block )
645
+ self .mu .Unlock ()
643
646
644
647
jsonlogger .LogJson (& logger.EthChainNewHead {
645
648
BlockHash : block .Hash ().Hex (),
@@ -747,9 +750,11 @@ func (self *ChainManager) merge(oldBlock, newBlock *types.Block) error {
747
750
}
748
751
749
752
// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
753
+ self .mu .Lock ()
750
754
for _ , block := range newChain {
751
755
self .insert (block )
752
756
}
757
+ self .mu .Unlock ()
753
758
754
759
return nil
755
760
}
0 commit comments