Skip to content

Commit 37564ce

Browse files
miner: refactor helper functions in worker.go (#21044)
This reduces complexity of some lengthy functions in worker.go, making the code easier to read.
1 parent 28c5a8a commit 37564ce

2 files changed

Lines changed: 52 additions & 41 deletions

File tree

‎consensus/clique/clique.go‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,8 @@ var (
137137
errRecentlySigned = errors.New("recently signed")
138138
)
139139

140-
// SignerFn is a signer callback function to request a header to be signed by a
141-
// backing account.
142-
type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
140+
// SignerFn hashes and signs the data to be signed by a backing account.
141+
type SignerFn func(signer accounts.Account, mimeType string, message []byte) ([]byte, error)
143142

144143
// ecrecover extracts the Ethereum account address from a signed header.
145144
func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {

‎miner/worker.go‎

Lines changed: 50 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,28 @@ func (w *worker) close() {
305305
close(w.exitCh)
306306
}
307307

308+
// recalcRecommit recalculates the resubmitting interval upon feedback.
309+
func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {
310+
var (
311+
prevF = float64(prev.Nanoseconds())
312+
next float64
313+
)
314+
if inc {
315+
next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
316+
max := float64(maxRecommitInterval.Nanoseconds())
317+
if next > max {
318+
next = max
319+
}
320+
} else {
321+
next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
322+
min := float64(minRecommit.Nanoseconds())
323+
if next < min {
324+
next = min
325+
}
326+
}
327+
return time.Duration(int64(next))
328+
}
329+
308330
// newWorkLoop is a standalone goroutine to submit new mining work upon received events.
309331
func (w *worker) newWorkLoop(recommit time.Duration) {
310332
var (
@@ -327,27 +349,6 @@ func (w *worker) newWorkLoop(recommit time.Duration) {
327349
timer.Reset(recommit)
328350
atomic.StoreInt32(&w.newTxs, 0)
329351
}
330-
// recalcRecommit recalculates the resubmitting interval upon feedback.
331-
recalcRecommit := func(target float64, inc bool) {
332-
var (
333-
prev = float64(recommit.Nanoseconds())
334-
next float64
335-
)
336-
if inc {
337-
next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
338-
// Recap if interval is larger than the maximum time interval
339-
if next > float64(maxRecommitInterval.Nanoseconds()) {
340-
next = float64(maxRecommitInterval.Nanoseconds())
341-
}
342-
} else {
343-
next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
344-
// Recap if interval is less than the user specified minimum
345-
if next < float64(minRecommit.Nanoseconds()) {
346-
next = float64(minRecommit.Nanoseconds())
347-
}
348-
}
349-
recommit = time.Duration(int64(next))
350-
}
351352
// clearPending cleans the stale pending tasks.
352353
clearPending := func(number uint64) {
353354
w.pendingMu.Lock()
@@ -400,11 +401,12 @@ func (w *worker) newWorkLoop(recommit time.Duration) {
400401
// Adjust resubmit interval by feedback.
401402
if adjust.inc {
402403
before := recommit
403-
recalcRecommit(float64(recommit.Nanoseconds())/adjust.ratio, true)
404+
target := float64(recommit.Nanoseconds()) / adjust.ratio
405+
recommit = recalcRecommit(minRecommit, recommit, target, true)
404406
log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
405407
} else {
406408
before := recommit
407-
recalcRecommit(float64(minRecommit.Nanoseconds()), false)
409+
recommit = recalcRecommit(minRecommit, recommit, float64(minRecommit.Nanoseconds()), false)
408410
log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
409411
}
410412

@@ -553,7 +555,7 @@ func (w *worker) taskLoop() {
553555
continue
554556
}
555557
w.pendingMu.Lock()
556-
w.pendingTasks[w.engine.SealHash(task.block.Header())] = task
558+
w.pendingTasks[sealHash] = task
557559
w.pendingMu.Unlock()
558560

559561
if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
@@ -974,13 +976,9 @@ func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64)
974976
// and commits new work if consensus engine is running.
975977
func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
976978
// Deep copy receipts here to avoid interaction between different tasks.
977-
receipts := make([]*types.Receipt, len(w.current.receipts))
978-
for i, l := range w.current.receipts {
979-
receipts[i] = new(types.Receipt)
980-
*receipts[i] = *l
981-
}
979+
receipts := copyReceipts(w.current.receipts)
982980
s := w.current.state.Copy()
983-
block, err := w.engine.FinalizeAndAssemble(w.chain, w.current.header, s, w.current.txs, uncles, w.current.receipts)
981+
block, err := w.engine.FinalizeAndAssemble(w.chain, w.current.header, s, w.current.txs, uncles, receipts)
984982
if err != nil {
985983
return err
986984
}
@@ -991,15 +989,10 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st
991989
select {
992990
case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}:
993991
w.unconfirmed.Shift(block.NumberU64() - 1)
994-
995-
feesWei := new(big.Int)
996-
for i, tx := range block.Transactions() {
997-
feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
998-
}
999-
feesEth := new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
1000-
1001992
log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
1002-
"uncles", len(uncles), "txs", w.current.tcount, "gas", block.GasUsed(), "fees", feesEth, "elapsed", common.PrettyDuration(time.Since(start)))
993+
"uncles", len(uncles), "txs", w.current.tcount,
994+
"gas", block.GasUsed(), "fees", totalFees(block, receipts),
995+
"elapsed", common.PrettyDuration(time.Since(start)))
1003996

1004997
case <-w.exitCh:
1005998
log.Info("Worker has exited")
@@ -1011,10 +1004,29 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st
10111004
return nil
10121005
}
10131006

1007+
// copyReceipts makes a deep copy of the given receipts.
1008+
func copyReceipts(receipts []*types.Receipt) []*types.Receipt {
1009+
result := make([]*types.Receipt, len(receipts))
1010+
for i, l := range receipts {
1011+
cpy := *l
1012+
result[i] = &cpy
1013+
}
1014+
return result
1015+
}
1016+
10141017
// postSideBlock fires a side chain event, only use it for testing.
10151018
func (w *worker) postSideBlock(event core.ChainSideEvent) {
10161019
select {
10171020
case w.chainSideCh <- event:
10181021
case <-w.exitCh:
10191022
}
10201023
}
1024+
1025+
// totalFees computes total consumed fees in ETH. Block transactions and receipts have to have the same order.
1026+
func totalFees(block *types.Block, receipts []*types.Receipt) *big.Float {
1027+
feesWei := new(big.Int)
1028+
for i, tx := range block.Transactions() {
1029+
feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
1030+
}
1031+
return new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
1032+
}

0 commit comments

Comments
 (0)