Skip to content

Commit 40a71f2

Browse files
rjl493456442karalabe
authored andcommitted
miner: fix state commit, track old work packages too (#17490)
* miner: commit state which is relative with sealing result * consensus, core, miner, mobile: introduce sealHash interface * miner: evict pending task with threshold * miner: go fmt
1 parent c3f7e3b commit 40a71f2

9 files changed

Lines changed: 113 additions & 74 deletions

File tree

‎consensus/clique/clique.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,11 @@ func CalcDifficulty(snap *Snapshot, signer common.Address) *big.Int {
673673
return new(big.Int).Set(diffNoTurn)
674674
}
675675

676+
// SealHash returns the hash of a block prior to it being sealed.
677+
func (c *Clique) SealHash(header *types.Header) common.Hash {
678+
return sigHash(header)
679+
}
680+
676681
// Close implements consensus.Engine. It's a noop for clique as there is are no background threads.
677682
func (c *Clique) Close() error {
678683
return nil

‎consensus/consensus.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,9 @@ type Engine interface {
9090
// seal place on top.
9191
Seal(chain ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error)
9292

93+
// SealHash returns the hash of a block prior to it being sealed.
94+
SealHash(header *types.Header) common.Hash
95+
9396
// CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
9497
// that a new block should have.
9598
CalcDifficulty(chain ChainReader, time uint64, parent *types.Header) *big.Int

‎consensus/ethash/consensus.go‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ import (
3131
"github.com/ethereum/go-ethereum/consensus/misc"
3232
"github.com/ethereum/go-ethereum/core/state"
3333
"github.com/ethereum/go-ethereum/core/types"
34+
"github.com/ethereum/go-ethereum/crypto/sha3"
3435
"github.com/ethereum/go-ethereum/params"
36+
"github.com/ethereum/go-ethereum/rlp"
3537
)
3638

3739
// Ethash proof-of-work protocol constants.
@@ -495,7 +497,7 @@ func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Head
495497
if fulldag {
496498
dataset := ethash.dataset(number, true)
497499
if dataset.generated() {
498-
digest, result = hashimotoFull(dataset.dataset, header.HashNoNonce().Bytes(), header.Nonce.Uint64())
500+
digest, result = hashimotoFull(dataset.dataset, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
499501

500502
// Datasets are unmapped in a finalizer. Ensure that the dataset stays alive
501503
// until after the call to hashimotoFull so it's not unmapped while being used.
@@ -513,7 +515,7 @@ func (ethash *Ethash) verifySeal(chain consensus.ChainReader, header *types.Head
513515
if ethash.config.PowMode == ModeTest {
514516
size = 32 * 1024
515517
}
516-
digest, result = hashimotoLight(size, cache.cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64())
518+
digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64())
517519

518520
// Caches are unmapped in a finalizer. Ensure that the cache stays alive
519521
// until after the call to hashimotoLight so it's not unmapped while being used.
@@ -552,6 +554,29 @@ func (ethash *Ethash) Finalize(chain consensus.ChainReader, header *types.Header
552554
return types.NewBlock(header, txs, uncles, receipts), nil
553555
}
554556

557+
// SealHash returns the hash of a block prior to it being sealed.
558+
func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
559+
hasher := sha3.NewKeccak256()
560+
561+
rlp.Encode(hasher, []interface{}{
562+
header.ParentHash,
563+
header.UncleHash,
564+
header.Coinbase,
565+
header.Root,
566+
header.TxHash,
567+
header.ReceiptHash,
568+
header.Bloom,
569+
header.Difficulty,
570+
header.Number,
571+
header.GasLimit,
572+
header.GasUsed,
573+
header.Time,
574+
header.Extra,
575+
})
576+
hasher.Sum(hash[:0])
577+
return hash
578+
}
579+
555580
// Some weird constants to avoid constant memory allocs for them.
556581
var (
557582
big8 = big.NewInt(8)

‎consensus/ethash/ethash_test.go‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ func TestRemoteSealer(t *testing.T) {
9494
}
9595
header := &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(100)}
9696
block := types.NewBlockWithHeader(header)
97+
sealhash := ethash.SealHash(header)
9798

9899
// Push new work.
99100
ethash.Seal(nil, block, nil)
@@ -102,27 +103,29 @@ func TestRemoteSealer(t *testing.T) {
102103
work [3]string
103104
err error
104105
)
105-
if work, err = api.GetWork(); err != nil || work[0] != block.HashNoNonce().Hex() {
106+
if work, err = api.GetWork(); err != nil || work[0] != sealhash.Hex() {
106107
t.Error("expect to return a mining work has same hash")
107108
}
108109

109-
if res := api.SubmitWork(types.BlockNonce{}, block.HashNoNonce(), common.Hash{}); res {
110+
if res := api.SubmitWork(types.BlockNonce{}, sealhash, common.Hash{}); res {
110111
t.Error("expect to return false when submit a fake solution")
111112
}
112113
// Push new block with same block number to replace the original one.
113114
header = &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(1000)}
114115
block = types.NewBlockWithHeader(header)
116+
sealhash = ethash.SealHash(header)
115117
ethash.Seal(nil, block, nil)
116118

117-
if work, err = api.GetWork(); err != nil || work[0] != block.HashNoNonce().Hex() {
119+
if work, err = api.GetWork(); err != nil || work[0] != sealhash.Hex() {
118120
t.Error("expect to return the latest pushed work")
119121
}
120122
// Push block with higher block number.
121123
newHead := &types.Header{Number: big.NewInt(2), Difficulty: big.NewInt(100)}
122124
newBlock := types.NewBlockWithHeader(newHead)
125+
newSealhash := ethash.SealHash(newHead)
123126
ethash.Seal(nil, newBlock, nil)
124127

125-
if res := api.SubmitWork(types.BlockNonce{}, block.HashNoNonce(), common.Hash{}); res {
128+
if res := api.SubmitWork(types.BlockNonce{}, newSealhash, common.Hash{}); res {
126129
t.Error("expect to return false when submit a stale solution")
127130
}
128131
}

‎consensus/ethash/sealer.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan s
111111
// Extract some data from the header
112112
var (
113113
header = block.Header()
114-
hash = header.HashNoNonce().Bytes()
114+
hash = ethash.SealHash(header).Bytes()
115115
target = new(big.Int).Div(two256, header.Difficulty)
116116
number = header.Number.Uint64()
117117
dataset = ethash.dataset(number, false)
@@ -213,7 +213,7 @@ func (ethash *Ethash) remote(notify []string) {
213213
// result[1], 32 bytes hex encoded seed hash used for DAG
214214
// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
215215
makeWork := func(block *types.Block) {
216-
hash := block.HashNoNonce()
216+
hash := ethash.SealHash(block.Header())
217217

218218
currentWork[0] = hash.Hex()
219219
currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex()

‎consensus/ethash/sealer_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func TestRemoteNotify(t *testing.T) {
5151
ethash.Seal(nil, block, nil)
5252
select {
5353
case work := <-sink:
54-
if want := header.HashNoNonce().Hex(); work[0] != want {
54+
if want := ethash.SealHash(header).Hex(); work[0] != want {
5555
t.Errorf("work packet hash mismatch: have %s, want %s", work[0], want)
5656
}
5757
if want := common.BytesToHash(SeedHash(header.Number.Uint64())).Hex(); work[1] != want {

‎core/types/block.go‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -102,25 +102,6 @@ func (h *Header) Hash() common.Hash {
102102
return rlpHash(h)
103103
}
104104

105-
// HashNoNonce returns the hash which is used as input for the proof-of-work search.
106-
func (h *Header) HashNoNonce() common.Hash {
107-
return rlpHash([]interface{}{
108-
h.ParentHash,
109-
h.UncleHash,
110-
h.Coinbase,
111-
h.Root,
112-
h.TxHash,
113-
h.ReceiptHash,
114-
h.Bloom,
115-
h.Difficulty,
116-
h.Number,
117-
h.GasLimit,
118-
h.GasUsed,
119-
h.Time,
120-
h.Extra,
121-
})
122-
}
123-
124105
// Size returns the approximate memory used by all internal contents. It is used
125106
// to approximate and limit the memory consumption of various caches.
126107
func (h *Header) Size() common.StorageSize {
@@ -324,10 +305,6 @@ func (b *Block) Header() *Header { return CopyHeader(b.header) }
324305
// Body returns the non-header content of the block.
325306
func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }
326307

327-
func (b *Block) HashNoNonce() common.Hash {
328-
return b.header.HashNoNonce()
329-
}
330-
331308
// Size returns the true RLP encoded storage size of the block, either by encoding
332309
// and returning it, or returning a previsouly cached value.
333310
func (b *Block) Size() common.StorageSize {

‎miner/worker.go‎

Lines changed: 52 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ const (
7272
// intervalAdjustBias is applied during the new resubmit interval calculation in favor of
7373
// increasing upper limit or decreasing lower limit so that the limit can be reachable.
7474
intervalAdjustBias = 200 * 1000.0 * 1000.0
75+
76+
// staleThreshold is the maximum distance of the acceptable stale block.
77+
staleThreshold = 7
7578
)
7679

7780
// environment is the worker's current environment and holds all of the current state information.
@@ -150,6 +153,9 @@ type worker struct {
150153
coinbase common.Address
151154
extra []byte
152155

156+
pendingMu sync.RWMutex
157+
pendingTasks map[common.Hash]*task
158+
153159
snapshotMu sync.RWMutex // The lock used to protect the block snapshot and state snapshot
154160
snapshotBlock *types.Block
155161
snapshotState *state.StateDB
@@ -174,6 +180,7 @@ func newWorker(config *params.ChainConfig, engine consensus.Engine, eth Backend,
174180
chain: eth.BlockChain(),
175181
possibleUncles: make(map[common.Hash]*types.Block),
176182
unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
183+
pendingTasks: make(map[common.Hash]*task),
177184
txsCh: make(chan core.NewTxsEvent, txChanSize),
178185
chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
179186
chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
@@ -317,13 +324,25 @@ func (w *worker) newWorkLoop(recommit time.Duration) {
317324
}
318325
recommit = time.Duration(int64(next))
319326
}
327+
// clearPending cleans the stale pending tasks.
328+
clearPending := func(number uint64) {
329+
w.pendingMu.Lock()
330+
for h, t := range w.pendingTasks {
331+
if t.block.NumberU64()+staleThreshold <= number {
332+
delete(w.pendingTasks, h)
333+
}
334+
}
335+
w.pendingMu.Unlock()
336+
}
320337

321338
for {
322339
select {
323340
case <-w.startCh:
341+
clearPending(w.chain.CurrentBlock().NumberU64())
324342
commit(false, commitInterruptNewHead)
325343

326-
case <-w.chainHeadCh:
344+
case head := <-w.chainHeadCh:
345+
clearPending(head.Block.NumberU64())
327346
commit(false, commitInterruptNewHead)
328347

329348
case <-timer.C:
@@ -454,28 +473,37 @@ func (w *worker) mainLoop() {
454473

455474
// seal pushes a sealing task to consensus engine and submits the result.
456475
func (w *worker) seal(t *task, stop <-chan struct{}) {
457-
var (
458-
err error
459-
res *task
460-
)
461-
462476
if w.skipSealHook != nil && w.skipSealHook(t) {
463477
return
464478
}
465-
466-
if t.block, err = w.engine.Seal(w.chain, t.block, stop); t.block != nil {
467-
log.Info("Successfully sealed new block", "number", t.block.Number(), "hash", t.block.Hash(),
468-
"elapsed", common.PrettyDuration(time.Since(t.createdAt)))
469-
res = t
470-
} else {
471-
if err != nil {
472-
log.Warn("Block sealing failed", "err", err)
479+
// The reason for caching task first is:
480+
// A previous sealing action will be canceled by subsequent actions,
481+
// however, remote miner may submit a result based on the cancelled task.
482+
// So we should only submit the pending state corresponding to the seal result.
483+
// TODO(rjl493456442) Replace the seal-wait logic structure
484+
w.pendingMu.Lock()
485+
w.pendingTasks[w.engine.SealHash(t.block.Header())] = t
486+
w.pendingMu.Unlock()
487+
488+
if block, err := w.engine.Seal(w.chain, t.block, stop); block != nil {
489+
sealhash := w.engine.SealHash(block.Header())
490+
w.pendingMu.RLock()
491+
task, exist := w.pendingTasks[sealhash]
492+
w.pendingMu.RUnlock()
493+
if !exist {
494+
log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", block.Hash())
495+
return
473496
}
474-
res = nil
475-
}
476-
select {
477-
case w.resultCh <- res:
478-
case <-w.exitCh:
497+
// Assemble sealing result
498+
task.block = block
499+
log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", block.Hash(),
500+
"elapsed", common.PrettyDuration(time.Since(task.createdAt)))
501+
select {
502+
case w.resultCh <- task:
503+
case <-w.exitCh:
504+
}
505+
} else if err != nil {
506+
log.Warn("Block sealing failed", "err", err)
479507
}
480508
}
481509

@@ -501,12 +529,13 @@ func (w *worker) taskLoop() {
501529
w.newTaskHook(task)
502530
}
503531
// Reject duplicate sealing work due to resubmitting.
504-
if task.block.HashNoNonce() == prev {
532+
sealHash := w.engine.SealHash(task.block.Header())
533+
if sealHash == prev {
505534
continue
506535
}
507536
interrupt()
508537
stopCh = make(chan struct{})
509-
prev = task.block.HashNoNonce()
538+
prev = sealHash
510539
go w.seal(task, stopCh)
511540
case <-w.exitCh:
512541
interrupt()
@@ -928,8 +957,8 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st
928957
}
929958
feesEth := new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
930959

931-
log.Info("Commit new mining work", "number", block.Number(), "uncles", len(uncles), "txs", w.current.tcount,
932-
"gas", block.GasUsed(), "fees", feesEth, "elapsed", common.PrettyDuration(time.Since(start)))
960+
log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
961+
"uncles", len(uncles), "txs", w.current.tcount, "gas", block.GasUsed(), "fees", feesEth, "elapsed", common.PrettyDuration(time.Since(start)))
933962

934963
case <-w.exitCh:
935964
log.Info("Worker has exited")

‎mobile/types.go‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -168,25 +168,22 @@ func (b *Block) EncodeJSON() (string, error) {
168168
return string(data), err
169169
}
170170

171-
func (b *Block) GetParentHash() *Hash { return &Hash{b.block.ParentHash()} }
172-
func (b *Block) GetUncleHash() *Hash { return &Hash{b.block.UncleHash()} }
173-
func (b *Block) GetCoinbase() *Address { return &Address{b.block.Coinbase()} }
174-
func (b *Block) GetRoot() *Hash { return &Hash{b.block.Root()} }
175-
func (b *Block) GetTxHash() *Hash { return &Hash{b.block.TxHash()} }
176-
func (b *Block) GetReceiptHash() *Hash { return &Hash{b.block.ReceiptHash()} }
177-
func (b *Block) GetBloom() *Bloom { return &Bloom{b.block.Bloom()} }
178-
func (b *Block) GetDifficulty() *BigInt { return &BigInt{b.block.Difficulty()} }
179-
func (b *Block) GetNumber() int64 { return b.block.Number().Int64() }
180-
func (b *Block) GetGasLimit() int64 { return int64(b.block.GasLimit()) }
181-
func (b *Block) GetGasUsed() int64 { return int64(b.block.GasUsed()) }
182-
func (b *Block) GetTime() int64 { return b.block.Time().Int64() }
183-
func (b *Block) GetExtra() []byte { return b.block.Extra() }
184-
func (b *Block) GetMixDigest() *Hash { return &Hash{b.block.MixDigest()} }
185-
func (b *Block) GetNonce() int64 { return int64(b.block.Nonce()) }
186-
187-
func (b *Block) GetHash() *Hash { return &Hash{b.block.Hash()} }
188-
func (b *Block) GetHashNoNonce() *Hash { return &Hash{b.block.HashNoNonce()} }
189-
171+
func (b *Block) GetParentHash() *Hash { return &Hash{b.block.ParentHash()} }
172+
func (b *Block) GetUncleHash() *Hash { return &Hash{b.block.UncleHash()} }
173+
func (b *Block) GetCoinbase() *Address { return &Address{b.block.Coinbase()} }
174+
func (b *Block) GetRoot() *Hash { return &Hash{b.block.Root()} }
175+
func (b *Block) GetTxHash() *Hash { return &Hash{b.block.TxHash()} }
176+
func (b *Block) GetReceiptHash() *Hash { return &Hash{b.block.ReceiptHash()} }
177+
func (b *Block) GetBloom() *Bloom { return &Bloom{b.block.Bloom()} }
178+
func (b *Block) GetDifficulty() *BigInt { return &BigInt{b.block.Difficulty()} }
179+
func (b *Block) GetNumber() int64 { return b.block.Number().Int64() }
180+
func (b *Block) GetGasLimit() int64 { return int64(b.block.GasLimit()) }
181+
func (b *Block) GetGasUsed() int64 { return int64(b.block.GasUsed()) }
182+
func (b *Block) GetTime() int64 { return b.block.Time().Int64() }
183+
func (b *Block) GetExtra() []byte { return b.block.Extra() }
184+
func (b *Block) GetMixDigest() *Hash { return &Hash{b.block.MixDigest()} }
185+
func (b *Block) GetNonce() int64 { return int64(b.block.Nonce()) }
186+
func (b *Block) GetHash() *Hash { return &Hash{b.block.Hash()} }
190187
func (b *Block) GetHeader() *Header { return &Header{b.block.Header()} }
191188
func (b *Block) GetUncles() *Headers { return &Headers{b.block.Uncles()} }
192189
func (b *Block) GetTransactions() *Transactions { return &Transactions{b.block.Transactions()} }

0 commit comments

Comments
 (0)