Skip to content

Commit 10b3f97

Browse files
authored
core: only fire one chain head per batch (#15123)
* core: only fire one chain head per batch * miner: announce chan events synchronously
1 parent 5596b66 commit 10b3f97

3 files changed

Lines changed: 63 additions & 67 deletions

File tree

‎core/blockchain.go‎

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -854,17 +854,30 @@ func (bc *BlockChain) WriteBlockAndState(block *types.Block, receipts []*types.R
854854
return status, nil
855855
}
856856

857-
// InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. If an error is returned
858-
// it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go).
857+
// InsertChain attempts to insert the given batch of blocks in to the canonical
858+
// chain or, otherwise, create a fork. If an error is returned it will return
859+
// the index number of the failing block as well an error describing what went
860+
// wrong.
861+
//
862+
// After insertion is done, all accumulated events will be fired.
859863
func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
864+
n, events, logs, err := bc.insertChain(chain)
865+
bc.PostChainEvents(events, logs)
866+
return n, err
867+
}
868+
869+
// insertChain will execute the actual chain insertion and event aggregation. The
870+
// only reason this method exists as a separate one is to make locking cleaner
871+
// with deferred statements.
872+
func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*types.Log, error) {
860873
// Do a sanity check that the provided chain is actually ordered and linked
861874
for i := 1; i < len(chain); i++ {
862875
if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
863876
// Chain broke ancestry, log a messge (programming error) and skip insertion
864877
log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
865878
"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
866879

867-
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
880+
return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
868881
chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
869882
}
870883
}
@@ -881,6 +894,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
881894
var (
882895
stats = insertStats{startTime: mclock.Now()}
883896
events = make([]interface{}, 0, len(chain))
897+
lastCanon *types.Block
884898
coalescedLogs []*types.Log
885899
)
886900
// Start the parallel header verifier
@@ -904,7 +918,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
904918
// If the header is a banned one, straight out abort
905919
if BadHashes[block.Hash()] {
906920
bc.reportBlock(block, nil, ErrBlacklistedHash)
907-
return i, ErrBlacklistedHash
921+
return i, events, coalescedLogs, ErrBlacklistedHash
908922
}
909923
// Wait for the block's verification to complete
910924
bstart := time.Now()
@@ -925,7 +939,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
925939
// if given.
926940
max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
927941
if block.Time().Cmp(max) > 0 {
928-
return i, fmt.Errorf("future block: %v > %v", block.Time(), max)
942+
return i, events, coalescedLogs, fmt.Errorf("future block: %v > %v", block.Time(), max)
929943
}
930944
bc.futureBlocks.Add(block.Hash(), block)
931945
stats.queued++
@@ -939,7 +953,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
939953
}
940954

941955
bc.reportBlock(block, nil, err)
942-
return i, err
956+
return i, events, coalescedLogs, err
943957
}
944958
// Create a new statedb using the parent block and report an
945959
// error if it fails.
@@ -951,40 +965,35 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
951965
}
952966
state, err := state.New(parent.Root(), bc.stateCache)
953967
if err != nil {
954-
return i, err
968+
return i, events, coalescedLogs, err
955969
}
956970
// Process block using the parent state as reference point.
957971
receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
958972
if err != nil {
959973
bc.reportBlock(block, receipts, err)
960-
return i, err
974+
return i, events, coalescedLogs, err
961975
}
962976
// Validate the state using the default validator
963977
err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas)
964978
if err != nil {
965979
bc.reportBlock(block, receipts, err)
966-
return i, err
980+
return i, events, coalescedLogs, err
967981
}
968-
969982
// Write the block to the chain and get the status.
970983
status, err := bc.WriteBlockAndState(block, receipts, state)
971984
if err != nil {
972-
return i, err
985+
return i, events, coalescedLogs, err
973986
}
974987
switch status {
975988
case CanonStatTy:
976989
log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()),
977990
"txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart)))
978-
// coalesce logs for later processing
991+
979992
coalescedLogs = append(coalescedLogs, logs...)
980993
blockInsertTimer.UpdateSince(bstart)
981994
events = append(events, ChainEvent{block, block.Hash(), logs})
982-
// We need some control over the mining operation. Acquiring locks and waiting
983-
// for the miner to create new block takes too long and in most cases isn't
984-
// even necessary.
985-
if bc.LastBlockHash() == block.Hash() {
986-
events = append(events, ChainHeadEvent{block})
987-
}
995+
lastCanon = block
996+
988997
case SideStatTy:
989998
log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed",
990999
common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()))
@@ -996,9 +1005,11 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
9961005
stats.usedGas += usedGas.Uint64()
9971006
stats.report(chain, i)
9981007
}
999-
go bc.PostChainEvents(events, coalescedLogs)
1000-
1001-
return 0, nil
1008+
// Append a single chain head event if we've progressed the chain
1009+
if lastCanon != nil && bc.LastBlockHash() == lastCanon.Hash() {
1010+
events = append(events, ChainHeadEvent{lastCanon})
1011+
}
1012+
return 0, events, coalescedLogs, nil
10021013
}
10031014

10041015
// insertStats tracks and reports on block insertion.

‎core/blockchain_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -935,7 +935,7 @@ func TestReorgSideEvent(t *testing.T) {
935935
}
936936
gen.AddTx(tx)
937937
})
938-
chainSideCh := make(chan ChainSideEvent)
938+
chainSideCh := make(chan ChainSideEvent, 64)
939939
blockchain.SubscribeChainSideEvent(chainSideCh)
940940
if _, err := blockchain.InsertChain(replacementBlocks); err != nil {
941941
t.Fatalf("failed to insert chain: %v", err)

‎miner/worker.go‎

Lines changed: 30 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,6 @@ type worker struct {
125125
// atomic status counters
126126
mining int32
127127
atWork int32
128-
129-
fullValidation bool
130128
}
131129

132130
func newWorker(config *params.ChainConfig, engine consensus.Engine, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
@@ -146,7 +144,6 @@ func newWorker(config *params.ChainConfig, engine consensus.Engine, coinbase com
146144
coinbase: coinbase,
147145
agents: make(map[Agent]struct{}),
148146
unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
149-
fullValidation: false,
150147
}
151148
// Subscribe TxPreEvent for tx pool
152149
worker.txSub = eth.TxPool().SubscribeTxPreEvent(worker.txCh)
@@ -297,50 +294,38 @@ func (self *worker) wait() {
297294
block := result.Block
298295
work := result.Work
299296

300-
if self.fullValidation {
301-
if _, err := self.chain.InsertChain(types.Blocks{block}); err != nil {
302-
log.Error("Mined invalid block", "err", err)
303-
continue
304-
}
305-
go self.mux.Post(core.NewMinedBlockEvent{Block: block})
306-
} else {
307-
// Update the block hash in all logs since it is now available and not when the
308-
// receipt/log of individual transactions were created.
309-
for _, r := range work.receipts {
310-
for _, l := range r.Logs {
311-
l.BlockHash = block.Hash()
312-
}
313-
}
314-
for _, log := range work.state.Logs() {
315-
log.BlockHash = block.Hash()
316-
}
317-
stat, err := self.chain.WriteBlockAndState(block, work.receipts, work.state)
318-
if err != nil {
319-
log.Error("Failed writing block to chain", "err", err)
320-
continue
321-
}
322-
323-
// check if canon block and write transactions
324-
if stat == core.CanonStatTy {
325-
// implicit by posting ChainHeadEvent
326-
mustCommitNewWork = false
297+
// Update the block hash in all logs since it is now available and not when the
298+
// receipt/log of individual transactions were created.
299+
for _, r := range work.receipts {
300+
for _, l := range r.Logs {
301+
l.BlockHash = block.Hash()
327302
}
328-
// broadcast before waiting for validation
329-
go func(block *types.Block, logs []*types.Log, receipts []*types.Receipt) {
330-
self.mux.Post(core.NewMinedBlockEvent{Block: block})
331-
var (
332-
events []interface{}
333-
coalescedLogs []*types.Log
334-
)
335-
events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
336-
if stat == core.CanonStatTy {
337-
events = append(events, core.ChainHeadEvent{Block: block})
338-
coalescedLogs = logs
339-
}
340-
// post blockchain events
341-
self.chain.PostChainEvents(events, coalescedLogs)
342-
}(block, work.state.Logs(), work.receipts)
343303
}
304+
for _, log := range work.state.Logs() {
305+
log.BlockHash = block.Hash()
306+
}
307+
stat, err := self.chain.WriteBlockAndState(block, work.receipts, work.state)
308+
if err != nil {
309+
log.Error("Failed writing block to chain", "err", err)
310+
continue
311+
}
312+
// check if canon block and write transactions
313+
if stat == core.CanonStatTy {
314+
// implicit by posting ChainHeadEvent
315+
mustCommitNewWork = false
316+
}
317+
// Broadcast the block and announce chain insertion event
318+
self.mux.Post(core.NewMinedBlockEvent{Block: block})
319+
var (
320+
events []interface{}
321+
logs = work.state.Logs()
322+
)
323+
events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
324+
if stat == core.CanonStatTy {
325+
events = append(events, core.ChainHeadEvent{Block: block})
326+
}
327+
self.chain.PostChainEvents(events, logs)
328+
344329
// Insert the block into the set of pending ones to wait for confirmations
345330
self.unconfirmed.Insert(block.NumberU64(), block.Hash())
346331

0 commit comments

Comments
 (0)