Skip to content

Commit c1c003e

Browse files
rjl493456442karalabe
authored andcommitted
consensus, miner: stale block mining support (#17506)
* consensus, miner: stale block supporting * consensus, miner: refactor seal signature * cmd, consensus, eth: add miner noverify flag * cmd, consensus, miner: polish
1 parent 63352bf commit c1c003e

16 files changed

Lines changed: 317 additions & 183 deletions

File tree

‎cmd/geth/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ var (
108108
utils.MinerExtraDataFlag,
109109
utils.MinerLegacyExtraDataFlag,
110110
utils.MinerRecommitIntervalFlag,
111+
utils.MinerNoVerfiyFlag,
111112
utils.NATFlag,
112113
utils.NoDiscoverFlag,
113114
utils.DiscoveryV5Flag,

‎cmd/geth/usage.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ var AppHelpFlagGroups = []flagGroup{
192192
utils.MinerEtherbaseFlag,
193193
utils.MinerExtraDataFlag,
194194
utils.MinerRecommitIntervalFlag,
195+
utils.MinerNoVerfiyFlag,
195196
},
196197
},
197198
{

‎cmd/utils/flags.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,9 +366,13 @@ var (
366366
}
367367
MinerRecommitIntervalFlag = cli.DurationFlag{
368368
Name: "miner.recommit",
369-
Usage: "Time interval to recreate the block being mined.",
369+
Usage: "Time interval to recreate the block being mined",
370370
Value: eth.DefaultConfig.MinerRecommit,
371371
}
372+
MinerNoVerfiyFlag = cli.BoolFlag{
373+
Name: "miner.noverify",
374+
Usage: "Disable remote sealing verification",
375+
}
372376
// Account settings
373377
UnlockedAccountFlag = cli.StringFlag{
374378
Name: "unlock",
@@ -1151,6 +1155,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
11511155
if ctx.GlobalIsSet(MinerRecommitIntervalFlag.Name) {
11521156
cfg.MinerRecommit = ctx.Duration(MinerRecommitIntervalFlag.Name)
11531157
}
1158+
if ctx.GlobalIsSet(MinerNoVerfiyFlag.Name) {
1159+
cfg.MinerNoverify = ctx.Bool(MinerNoVerfiyFlag.Name)
1160+
}
11541161
if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
11551162
// TODO(fjl): force-enable this in --dev mode
11561163
cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
@@ -1345,7 +1352,7 @@ func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chai
13451352
DatasetDir: stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
13461353
DatasetsInMem: eth.DefaultConfig.Ethash.DatasetsInMem,
13471354
DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
1348-
}, nil)
1355+
}, nil, false)
13491356
}
13501357
}
13511358
if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {

‎consensus/clique/clique.go‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -590,17 +590,17 @@ func (c *Clique) Authorize(signer common.Address, signFn SignerFn) {
590590

591591
// Seal implements consensus.Engine, attempting to create a sealed block using
592592
// the local signing credentials.
593-
func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
593+
func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
594594
header := block.Header()
595595

596596
// Sealing the genesis block is not supported
597597
number := header.Number.Uint64()
598598
if number == 0 {
599-
return nil, errUnknownBlock
599+
return errUnknownBlock
600600
}
601601
// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
602602
if c.config.Period == 0 && len(block.Transactions()) == 0 {
603-
return nil, errWaitTransactions
603+
return errWaitTransactions
604604
}
605605
// Don't hold the signer fields for the entire sealing procedure
606606
c.lock.RLock()
@@ -610,19 +610,18 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-ch
610610
// Bail out if we're unauthorized to sign a block
611611
snap, err := c.snapshot(chain, number-1, header.ParentHash, nil)
612612
if err != nil {
613-
return nil, err
613+
return err
614614
}
615615
if _, authorized := snap.Signers[signer]; !authorized {
616-
return nil, errUnauthorized
616+
return errUnauthorized
617617
}
618618
// If we're amongst the recent signers, wait for the next block
619619
for seen, recent := range snap.Recents {
620620
if recent == signer {
621621
// Signer is among recents, only wait if the current block doesn't shift it out
622622
if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
623623
log.Info("Signed recently, must wait for others")
624-
<-stop
625-
return nil, nil
624+
return nil
626625
}
627626
}
628627
}
@@ -635,21 +634,29 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-ch
635634

636635
log.Trace("Out-of-turn signing requested", "wiggle", common.PrettyDuration(wiggle))
637636
}
638-
log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
639-
640-
select {
641-
case <-stop:
642-
return nil, nil
643-
case <-time.After(delay):
644-
}
645637
// Sign all the things!
646638
sighash, err := signFn(accounts.Account{Address: signer}, sigHash(header).Bytes())
647639
if err != nil {
648-
return nil, err
640+
return err
649641
}
650642
copy(header.Extra[len(header.Extra)-extraSeal:], sighash)
643+
// Wait until sealing is terminated or delay timeout.
644+
log.Trace("Waiting for slot to sign and propagate", "delay", common.PrettyDuration(delay))
645+
go func() {
646+
select {
647+
case <-stop:
648+
return
649+
case <-time.After(delay):
650+
}
651651

652-
return block.WithSeal(header), nil
652+
select {
653+
case results <- block.WithSeal(header):
654+
default:
655+
log.Warn("Sealing result is not read by miner", "sealhash", c.SealHash(header))
656+
}
657+
}()
658+
659+
return nil
653660
}
654661

655662
// CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty

‎consensus/consensus.go‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,12 @@ type Engine interface {
8686
Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction,
8787
uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)
8888

89-
// Seal generates a new block for the given input block with the local miner's
90-
// seal place on top.
91-
Seal(chain ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error)
89+
// Seal generates a new sealing request for the given input block and pushes
90+
// the result into the given channel.
91+
//
92+
// Note, the method returns immediately and will send the result async. More
93+
// than one result may also be returned depending on the consensus algorothm.
94+
Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error
9295

9396
// SealHash returns the hash of a block prior to it being sealed.
9497
SealHash(header *types.Header) common.Hash

‎consensus/ethash/algorithm_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -729,7 +729,7 @@ func TestConcurrentDiskCacheGeneration(t *testing.T) {
729729

730730
go func(idx int) {
731731
defer pend.Done()
732-
ethash := New(Config{cachedir, 0, 1, "", 0, 0, ModeNormal}, nil)
732+
ethash := New(Config{cachedir, 0, 1, "", 0, 0, ModeNormal}, nil, false)
733733
defer ethash.Close()
734734
if err := ethash.VerifySeal(nil, block.Header()); err != nil {
735735
t.Errorf("proc %d: block verification failed: %v", idx, err)

‎consensus/ethash/ethash.go‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ var (
5050
two256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
5151

5252
// sharedEthash is a full instance that can be shared between multiple users.
53-
sharedEthash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}, nil)
53+
sharedEthash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}, nil, false)
5454

5555
// algorithmRevision is the data structure version used for file naming.
5656
algorithmRevision = 23
@@ -405,6 +405,12 @@ type Config struct {
405405
PowMode Mode
406406
}
407407

408+
// sealTask wraps a seal block with relative result channel for remote sealer thread.
409+
type sealTask struct {
410+
block *types.Block
411+
results chan<- *types.Block
412+
}
413+
408414
// mineResult wraps the pow solution parameters for the specified block.
409415
type mineResult struct {
410416
nonce types.BlockNonce
@@ -444,12 +450,11 @@ type Ethash struct {
444450
hashrate metrics.Meter // Meter tracking the average hashrate
445451

446452
// Remote sealer related fields
447-
workCh chan *types.Block // Notification channel to push new work to remote sealer
448-
resultCh chan *types.Block // Channel used by mining threads to return result
449-
fetchWorkCh chan *sealWork // Channel used for remote sealer to fetch mining work
450-
submitWorkCh chan *mineResult // Channel used for remote sealer to submit their mining result
451-
fetchRateCh chan chan uint64 // Channel used to gather submitted hash rate for local or remote sealer.
452-
submitRateCh chan *hashrate // Channel used for remote sealer to submit their mining hashrate
453+
workCh chan *sealTask // Notification channel to push new work and relative result channel to remote sealer
454+
fetchWorkCh chan *sealWork // Channel used for remote sealer to fetch mining work
455+
submitWorkCh chan *mineResult // Channel used for remote sealer to submit their mining result
456+
fetchRateCh chan chan uint64 // Channel used to gather submitted hash rate for local or remote sealer.
457+
submitRateCh chan *hashrate // Channel used for remote sealer to submit their mining hashrate
453458

454459
// The fields below are hooks for testing
455460
shared *Ethash // Shared PoW verifier to avoid cache regeneration
@@ -464,7 +469,7 @@ type Ethash struct {
464469
// New creates a full sized ethash PoW scheme and starts a background thread for
465470
// remote mining, also optionally notifying a batch of remote services of new work
466471
// packages.
467-
func New(config Config, notify []string) *Ethash {
472+
func New(config Config, notify []string, noverify bool) *Ethash {
468473
if config.CachesInMem <= 0 {
469474
log.Warn("One ethash cache must always be in memory", "requested", config.CachesInMem)
470475
config.CachesInMem = 1
@@ -481,36 +486,34 @@ func New(config Config, notify []string) *Ethash {
481486
datasets: newlru("dataset", config.DatasetsInMem, newDataset),
482487
update: make(chan struct{}),
483488
hashrate: metrics.NewMeter(),
484-
workCh: make(chan *types.Block),
485-
resultCh: make(chan *types.Block),
489+
workCh: make(chan *sealTask),
486490
fetchWorkCh: make(chan *sealWork),
487491
submitWorkCh: make(chan *mineResult),
488492
fetchRateCh: make(chan chan uint64),
489493
submitRateCh: make(chan *hashrate),
490494
exitCh: make(chan chan error),
491495
}
492-
go ethash.remote(notify)
496+
go ethash.remote(notify, noverify)
493497
return ethash
494498
}
495499

496500
// NewTester creates a small sized ethash PoW scheme useful only for testing
497501
// purposes.
498-
func NewTester(notify []string) *Ethash {
502+
func NewTester(notify []string, noverify bool) *Ethash {
499503
ethash := &Ethash{
500504
config: Config{PowMode: ModeTest},
501505
caches: newlru("cache", 1, newCache),
502506
datasets: newlru("dataset", 1, newDataset),
503507
update: make(chan struct{}),
504508
hashrate: metrics.NewMeter(),
505-
workCh: make(chan *types.Block),
506-
resultCh: make(chan *types.Block),
509+
workCh: make(chan *sealTask),
507510
fetchWorkCh: make(chan *sealWork),
508511
submitWorkCh: make(chan *mineResult),
509512
fetchRateCh: make(chan chan uint64),
510513
submitRateCh: make(chan *hashrate),
511514
exitCh: make(chan chan error),
512515
}
513-
go ethash.remote(notify)
516+
go ethash.remote(notify, noverify)
514517
return ethash
515518
}
516519

‎consensus/ethash/ethash_test.go‎

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,23 @@ import (
3434
func TestTestMode(t *testing.T) {
3535
header := &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(100)}
3636

37-
ethash := NewTester(nil)
37+
ethash := NewTester(nil, false)
3838
defer ethash.Close()
3939

40-
block, err := ethash.Seal(nil, types.NewBlockWithHeader(header), nil)
40+
results := make(chan *types.Block)
41+
err := ethash.Seal(nil, types.NewBlockWithHeader(header), results, nil)
4142
if err != nil {
4243
t.Fatalf("failed to seal block: %v", err)
4344
}
44-
header.Nonce = types.EncodeNonce(block.Nonce())
45-
header.MixDigest = block.MixDigest()
46-
if err := ethash.VerifySeal(nil, header); err != nil {
47-
t.Fatalf("unexpected verification error: %v", err)
45+
select {
46+
case block := <-results:
47+
header.Nonce = types.EncodeNonce(block.Nonce())
48+
header.MixDigest = block.MixDigest()
49+
if err := ethash.VerifySeal(nil, header); err != nil {
50+
t.Fatalf("unexpected verification error: %v", err)
51+
}
52+
case <-time.NewTimer(time.Second).C:
53+
t.Error("sealing result timeout")
4854
}
4955
}
5056

@@ -56,7 +62,7 @@ func TestCacheFileEvict(t *testing.T) {
5662
t.Fatal(err)
5763
}
5864
defer os.RemoveAll(tmpdir)
59-
e := New(Config{CachesInMem: 3, CachesOnDisk: 10, CacheDir: tmpdir, PowMode: ModeTest}, nil)
65+
e := New(Config{CachesInMem: 3, CachesOnDisk: 10, CacheDir: tmpdir, PowMode: ModeTest}, nil, false)
6066
defer e.Close()
6167

6268
workers := 8
@@ -85,7 +91,7 @@ func verifyTest(wg *sync.WaitGroup, e *Ethash, workerIndex, epochs int) {
8591
}
8692

8793
func TestRemoteSealer(t *testing.T) {
88-
ethash := NewTester(nil)
94+
ethash := NewTester(nil, false)
8995
defer ethash.Close()
9096

9197
api := &API{ethash}
@@ -97,7 +103,8 @@ func TestRemoteSealer(t *testing.T) {
97103
sealhash := ethash.SealHash(header)
98104

99105
// Push new work.
100-
ethash.Seal(nil, block, nil)
106+
results := make(chan *types.Block)
107+
ethash.Seal(nil, block, results, nil)
101108

102109
var (
103110
work [3]string
@@ -114,20 +121,11 @@ func TestRemoteSealer(t *testing.T) {
114121
header = &types.Header{Number: big.NewInt(1), Difficulty: big.NewInt(1000)}
115122
block = types.NewBlockWithHeader(header)
116123
sealhash = ethash.SealHash(header)
117-
ethash.Seal(nil, block, nil)
124+
ethash.Seal(nil, block, results, nil)
118125

119126
if work, err = api.GetWork(); err != nil || work[0] != sealhash.Hex() {
120127
t.Error("expect to return the latest pushed work")
121128
}
122-
// Push block with higher block number.
123-
newHead := &types.Header{Number: big.NewInt(2), Difficulty: big.NewInt(100)}
124-
newBlock := types.NewBlockWithHeader(newHead)
125-
newSealhash := ethash.SealHash(newHead)
126-
ethash.Seal(nil, newBlock, nil)
127-
128-
if res := api.SubmitWork(types.BlockNonce{}, newSealhash, common.Hash{}); res {
129-
t.Error("expect to return false when submit a stale solution")
130-
}
131129
}
132130

133131
func TestHashRate(t *testing.T) {
@@ -136,7 +134,7 @@ func TestHashRate(t *testing.T) {
136134
expect uint64
137135
ids = []common.Hash{common.HexToHash("a"), common.HexToHash("b"), common.HexToHash("c")}
138136
)
139-
ethash := NewTester(nil)
137+
ethash := NewTester(nil, false)
140138
defer ethash.Close()
141139

142140
if tot := ethash.Hashrate(); tot != 0 {
@@ -156,7 +154,7 @@ func TestHashRate(t *testing.T) {
156154
}
157155

158156
func TestClosedRemoteSealer(t *testing.T) {
159-
ethash := NewTester(nil)
157+
ethash := NewTester(nil, false)
160158
time.Sleep(1 * time.Second) // ensure exit channel is listening
161159
ethash.Close()
162160

0 commit comments

Comments
 (0)