eth, consensus: minor polish

This commit is contained in:
rjl493456442 2017-11-23 21:37:10 +08:00
parent 533e03ea23
commit 8913f67f8e
10 changed files with 88 additions and 69 deletions

View file

@ -1159,10 +1159,14 @@ func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chai
} else { } else {
engine = ethash.NewFaker() engine = ethash.NewFaker()
if !ctx.GlobalBool(FakePoWFlag.Name) { if !ctx.GlobalBool(FakePoWFlag.Name) {
engine = ethash.New( engine = ethash.New(ethash.Config{
stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir), eth.DefaultConfig.Ethash.CachesInMem, eth.DefaultConfig.Ethash.CachesOnDisk, CacheDir: stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir),
stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir), eth.DefaultConfig.Ethash.DatasetsInMem, eth.DefaultConfig.Ethash.DatasetsOnDisk, CachesInMem: eth.DefaultConfig.Ethash.CachesInMem,
) CachesOnDisk: eth.DefaultConfig.Ethash.CachesOnDisk,
DatasetDir: stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
DatasetsInMem: eth.DefaultConfig.Ethash.DatasetsInMem,
DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
})
} }
} }
vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)} vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}

View file

@ -703,8 +703,7 @@ func TestConcurrentDiskCacheGeneration(t *testing.T) {
go func(idx int) { go func(idx int) {
defer pend.Done() defer pend.Done()
ethash := New(Config{cachedir, 0, 1, "", 0, 0, false, false, false, false})
ethash := New(cachedir, 0, 1, "", 0, 0)
if err := ethash.VerifySeal(nil, block.Header()); err != nil { if err := ethash.VerifySeal(nil, block.Header()); err != nil {
t.Errorf("proc %d: block verification failed: %v", idx, err) t.Errorf("proc %d: block verification failed: %v", idx, err)
} }

View file

@ -68,7 +68,7 @@ func (ethash *Ethash) Author(header *types.Header) (common.Address, error) {
// stock Ethereum ethash engine. // stock Ethereum ethash engine.
func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error { func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
// If we're running a full engine faking, accept any input as valid // If we're running a full engine faking, accept any input as valid
if ethash.fakeFull { if ethash.config.FullFake {
return nil return nil
} }
// Short circuit if the header is known, or it's parent not // Short circuit if the header is known, or it's parent not
@ -89,7 +89,7 @@ func (ethash *Ethash) VerifyHeader(chain consensus.ChainReader, header *types.He
// a results channel to retrieve the async verifications. // a results channel to retrieve the async verifications.
func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) { func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
// If we're running a full engine faking, accept any input as valid // If we're running a full engine faking, accept any input as valid
if ethash.fakeFull || len(headers) == 0 { if ethash.config.FullFake || len(headers) == 0 {
abort, results := make(chan struct{}), make(chan error, len(headers)) abort, results := make(chan struct{}), make(chan error, len(headers))
for i := 0; i < len(headers); i++ { for i := 0; i < len(headers); i++ {
results <- nil results <- nil
@ -169,7 +169,7 @@ func (ethash *Ethash) verifyHeaderWorker(chain consensus.ChainReader, headers []
// rules of the stock Ethereum ethash engine. // rules of the stock Ethereum ethash engine.
func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error { func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
// If we're running a full engine faking, accept any input as valid // If we're running a full engine faking, accept any input as valid
if ethash.fakeFull { if ethash.config.FullFake {
return nil return nil
} }
// Verify that there are at most 2 uncles included in this block // Verify that there are at most 2 uncles included in this block
@ -455,7 +455,7 @@ func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
// the PoW difficulty requirements. // the PoW difficulty requirements.
func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
// If we're running a fake PoW, accept any seal as valid // If we're running a fake PoW, accept any seal as valid
if ethash.fakeMode { if ethash.config.Fake {
time.Sleep(ethash.fakeDelay) time.Sleep(ethash.fakeDelay)
if ethash.fakeFail == header.Number.Uint64() { if ethash.fakeFail == header.Number.Uint64() {
return errInvalidPoW return errInvalidPoW
@ -480,7 +480,7 @@ func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Head
cache := ethash.cache(number) cache := ethash.cache(number)
size := datasetSize(number) size := datasetSize(number)
if ethash.tester { if ethash.config.Test {
size = 32 * 1024 size = 32 * 1024
} }
digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64()) digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64())

View file

@ -45,7 +45,7 @@ var (
maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0)) maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
// sharedEthash is a full instance that can be shared between multiple users. // sharedEthash is a full instance that can be shared between multiple users.
sharedEthash = New("", 3, 0, "", 1, 0) sharedEthash = New(Config{"", 3, 0, "", 1, 0, false, false, false, false})
// algorithmRevision is the data structure version used for file naming. // algorithmRevision is the data structure version used for file naming.
algorithmRevision = 23 algorithmRevision = 23
@ -320,8 +320,8 @@ func MakeDataset(block uint64, dir string) {
d.release() d.release()
} }
// EthashConfig are the configuration parameters of the ethash. // Config are the configuration parameters of the ethash.
type EthashConfig struct { type Config struct {
CacheDir string CacheDir string
CachesInMem int CachesInMem int
CachesOnDisk int CachesOnDisk int
@ -329,16 +329,17 @@ type EthashConfig struct {
DatasetsInMem int DatasetsInMem int
DatasetsOnDisk int DatasetsOnDisk int
// Miscellaneous options // The fields below are configurations for testing
PowFake bool Fake bool
PowTest bool FullFake bool
PowShared bool Test bool
Shared bool
} }
// Ethash is a consensus engine based on proot-of-work implementing the ethash // Ethash is a consensus engine based on proot-of-work implementing the ethash
// algorithm. // algorithm.
type Ethash struct { type Ethash struct {
EthashConfig config Config
caches map[uint64]*cache // In memory caches to avoid regenerating too often caches map[uint64]*cache // In memory caches to avoid regenerating too often
fcache *cache // Pre-generated cache for the estimated future epoch fcache *cache // Pre-generated cache for the estimated future epoch
@ -352,10 +353,7 @@ type Ethash struct {
hashrate metrics.Meter // Meter tracking the average hashrate hashrate metrics.Meter // Meter tracking the average hashrate
// The fields below are hooks for testing // The fields below are hooks for testing
tester bool // Flag whether to use a smaller test dataset
shared *Ethash // Shared PoW verifier to avoid cache regeneration shared *Ethash // Shared PoW verifier to avoid cache regeneration
fakeMode bool // Flag whether to disable PoW checking
fakeFull bool // Flag whether to disable all consensus rules
fakeFail uint64 // Block number which fails PoW check even in fake mode fakeFail uint64 // Block number which fails PoW check even in fake mode
fakeDelay time.Duration // Time delay to sleep for before returning from verify fakeDelay time.Duration // Time delay to sleep for before returning from verify
@ -363,26 +361,19 @@ type Ethash struct {
} }
// New creates a full sized ethash PoW scheme. // New creates a full sized ethash PoW scheme.
func New(cachedir string, cachesinmem, cachesondisk int, dagdir string, dagsinmem, dagsondisk int) *Ethash { func New(config Config) *Ethash {
if cachesinmem <= 0 { if config.CachesInMem <= 0 {
log.Warn("One ethash cache must always be in memory", "requested", cachesinmem) log.Warn("One ethash cache must always be in memory", "requested", config.CachesInMem)
cachesinmem = 1 config.CachesInMem = 1
} }
if cachedir != "" && cachesondisk > 0 { if config.CacheDir != "" && config.CachesOnDisk > 0 {
log.Info("Disk storage enabled for ethash caches", "dir", cachedir, "count", cachesondisk) log.Info("Disk storage enabled for ethash caches", "dir", config.CacheDir, "count", config.CachesOnDisk)
} }
if dagdir != "" && dagsondisk > 0 { if config.DatasetDir != "" && config.DatasetsOnDisk > 0 {
log.Info("Disk storage enabled for ethash DAGs", "dir", dagdir, "count", dagsondisk) log.Info("Disk storage enabled for ethash DAGs", "dir", config.DatasetDir, "count", config.DatasetsOnDisk)
} }
return &Ethash{ return &Ethash{
EthashConfig: EthashConfig{ config: config,
CacheDir: cachedir,
CachesInMem: cachesinmem,
CachesOnDisk: cachesondisk,
DatasetDir: dagdir,
DatasetsInMem: dagsinmem,
DatasetsOnDisk: dagsondisk,
},
caches: make(map[uint64]*cache), caches: make(map[uint64]*cache),
datasets: make(map[uint64]*dataset), datasets: make(map[uint64]*dataset),
update: make(chan struct{}), update: make(chan struct{}),
@ -394,12 +385,12 @@ func New(cachedir string, cachesinmem, cachesondisk int, dagdir string, dagsinme
// purposes. // purposes.
func NewTester() *Ethash { func NewTester() *Ethash {
return &Ethash{ return &Ethash{
EthashConfig: EthashConfig{ config: Config{
CachesInMem: 1, CachesInMem: 1,
Test: true,
}, },
caches: make(map[uint64]*cache), caches: make(map[uint64]*cache),
datasets: make(map[uint64]*dataset), datasets: make(map[uint64]*dataset),
tester: true,
update: make(chan struct{}), update: make(chan struct{}),
hashrate: metrics.NewMeter(), hashrate: metrics.NewMeter(),
} }
@ -409,27 +400,46 @@ func NewTester() *Ethash {
// all blocks' seal as valid, though they still have to conform to the Ethereum // all blocks' seal as valid, though they still have to conform to the Ethereum
// consensus rules. // consensus rules.
func NewFaker() *Ethash { func NewFaker() *Ethash {
return &Ethash{fakeMode: true} return &Ethash{
config: Config{
Fake: true,
},
}
} }
// NewFakeFailer creates a ethash consensus engine with a fake PoW scheme that // NewFakeFailer creates a ethash consensus engine with a fake PoW scheme that
// accepts all blocks as valid apart from the single one specified, though they // accepts all blocks as valid apart from the single one specified, though they
// still have to conform to the Ethereum consensus rules. // still have to conform to the Ethereum consensus rules.
func NewFakeFailer(fail uint64) *Ethash { func NewFakeFailer(fail uint64) *Ethash {
return &Ethash{fakeMode: true, fakeFail: fail} return &Ethash{
config: Config{
Fake: true,
},
fakeFail: fail,
}
} }
// NewFakeDelayer creates a ethash consensus engine with a fake PoW scheme that // NewFakeDelayer creates a ethash consensus engine with a fake PoW scheme that
// accepts all blocks as valid, but delays verifications by some time, though // accepts all blocks as valid, but delays verifications by some time, though
// they still have to conform to the Ethereum consensus rules. // they still have to conform to the Ethereum consensus rules.
func NewFakeDelayer(delay time.Duration) *Ethash { func NewFakeDelayer(delay time.Duration) *Ethash {
return &Ethash{fakeMode: true, fakeDelay: delay} return &Ethash{
config: Config{
Fake: true,
},
fakeDelay: delay,
}
} }
// NewFullFaker creates an ethash consensus engine with a full fake scheme that // NewFullFaker creates an ethash consensus engine with a full fake scheme that
// accepts all blocks as valid, without checking any consensus rules whatsoever. // accepts all blocks as valid, without checking any consensus rules whatsoever.
func NewFullFaker() *Ethash { func NewFullFaker() *Ethash {
return &Ethash{fakeMode: true, fakeFull: true} return &Ethash{
config: Config{
Fake: true,
FullFake: true,
},
}
} }
// NewShared creates a full sized ethash PoW shared between all requesters running // NewShared creates a full sized ethash PoW shared between all requesters running
@ -450,7 +460,7 @@ func (ethash *Ethash) cache(block uint64) []uint32 {
current, future := ethash.caches[epoch], (*cache)(nil) current, future := ethash.caches[epoch], (*cache)(nil)
if current == nil { if current == nil {
// No in-memory cache, evict the oldest if the cache limit was reached // No in-memory cache, evict the oldest if the cache limit was reached
for len(ethash.caches) > 0 && len(ethash.caches) >= ethash.CachesInMem { for len(ethash.caches) > 0 && len(ethash.caches) >= ethash.config.CachesInMem {
var evict *cache var evict *cache
for _, cache := range ethash.caches { for _, cache := range ethash.caches {
if evict == nil || evict.used.After(cache.used) { if evict == nil || evict.used.After(cache.used) {
@ -487,7 +497,7 @@ func (ethash *Ethash) cache(block uint64) []uint32 {
ethash.lock.Unlock() ethash.lock.Unlock()
// Wait for generation finish, bump the timestamp and finalize the cache // Wait for generation finish, bump the timestamp and finalize the cache
current.generate(ethash.CacheDir, ethash.CachesOnDisk, ethash.tester) current.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.Test)
current.lock.Lock() current.lock.Lock()
current.used = time.Now() current.used = time.Now()
@ -495,7 +505,7 @@ func (ethash *Ethash) cache(block uint64) []uint32 {
// If we exhausted the future cache, now's a good time to regenerate it // If we exhausted the future cache, now's a good time to regenerate it
if future != nil { if future != nil {
go future.generate(ethash.CacheDir, ethash.CachesOnDisk, ethash.tester) go future.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.Test)
} }
return current.cache return current.cache
} }
@ -512,7 +522,7 @@ func (ethash *Ethash) dataset(block uint64) []uint32 {
current, future := ethash.datasets[epoch], (*dataset)(nil) current, future := ethash.datasets[epoch], (*dataset)(nil)
if current == nil { if current == nil {
// No in-memory dataset, evict the oldest if the dataset limit was reached // No in-memory dataset, evict the oldest if the dataset limit was reached
for len(ethash.datasets) > 0 && len(ethash.datasets) >= ethash.DatasetsInMem { for len(ethash.datasets) > 0 && len(ethash.datasets) >= ethash.config.DatasetsInMem {
var evict *dataset var evict *dataset
for _, dataset := range ethash.datasets { for _, dataset := range ethash.datasets {
if evict == nil || evict.used.After(dataset.used) { if evict == nil || evict.used.After(dataset.used) {
@ -550,7 +560,7 @@ func (ethash *Ethash) dataset(block uint64) []uint32 {
ethash.lock.Unlock() ethash.lock.Unlock()
// Wait for generation finish, bump the timestamp and finalize the cache // Wait for generation finish, bump the timestamp and finalize the cache
current.generate(ethash.DatasetDir, ethash.DatasetsOnDisk, ethash.tester) current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.Test)
current.lock.Lock() current.lock.Lock()
current.used = time.Now() current.used = time.Now()
@ -558,7 +568,7 @@ func (ethash *Ethash) dataset(block uint64) []uint32 {
// If we exhausted the future dataset, now's a good time to regenerate it // If we exhausted the future dataset, now's a good time to regenerate it
if future != nil { if future != nil {
go future.generate(ethash.DatasetDir, ethash.DatasetsOnDisk, ethash.tester) go future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.Test)
} }
return current.dataset return current.dataset
} }

View file

@ -34,7 +34,7 @@ import (
// the block's difficulty requirements. // the block's difficulty requirements.
func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) { func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
// If we're running a fake PoW, simply return a 0 nonce immediately // If we're running a fake PoW, simply return a 0 nonce immediately
if ethash.fakeMode { if ethash.config.Fake {
header := block.Header() header := block.Header()
header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{} header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
return block.WithSeal(header), nil return block.WithSeal(header), nil

View file

@ -97,8 +97,8 @@ func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
ethConf := &eth.Config{ ethConf := &eth.Config{
Genesis: core.DeveloperGenesisBlock(15, common.Address{}), Genesis: core.DeveloperGenesisBlock(15, common.Address{}),
Etherbase: common.HexToAddress(testAddress), Etherbase: common.HexToAddress(testAddress),
Ethash: ethash.EthashConfig{ Ethash: ethash.Config{
PowTest: true, Test: true,
}, },
} }
if confOverride != nil { if confOverride != nil {

View file

@ -125,7 +125,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
chainConfig: chainConfig, chainConfig: chainConfig,
eventMux: ctx.EventMux, eventMux: ctx.EventMux,
accountManager: ctx.AccountManager, accountManager: ctx.AccountManager,
engine: CreateConsensusEngine(ctx, config, chainConfig, chainDb), engine: CreateConsensusEngine(ctx, &config.Ethash, chainConfig, chainDb),
shutdownChan: make(chan bool), shutdownChan: make(chan bool),
stopDbUpgrade: stopDbUpgrade, stopDbUpgrade: stopDbUpgrade,
networkId: config.NetworkId, networkId: config.NetworkId,
@ -209,25 +209,31 @@ func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Data
} }
// CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
func CreateConsensusEngine(ctx *node.ServiceContext, config *Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine { func CreateConsensusEngine(ctx *node.ServiceContext, config *ethash.Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
// If proof-of-authority is requested, set it up // If proof-of-authority is requested, set it up
if chainConfig.Clique != nil { if chainConfig.Clique != nil {
return clique.New(chainConfig.Clique, db) return clique.New(chainConfig.Clique, db)
} }
// Otherwise assume proof-of-work // Otherwise assume proof-of-work
switch { switch {
case config.Ethash.PowFake: case config.Fake:
log.Warn("Ethash used in fake mode") log.Warn("Ethash used in fake mode")
return ethash.NewFaker() return ethash.NewFaker()
case config.Ethash.PowTest: case config.Test:
log.Warn("Ethash used in test mode") log.Warn("Ethash used in test mode")
return ethash.NewTester() return ethash.NewTester()
case config.Ethash.PowShared: case config.Shared:
log.Warn("Ethash used in shared mode") log.Warn("Ethash used in shared mode")
return ethash.NewShared() return ethash.NewShared()
default: default:
engine := ethash.New(ctx.ResolvePath(config.Ethash.CacheDir), config.Ethash.CachesInMem, config.Ethash.CachesOnDisk, engine := ethash.New(ethash.Config{
config.Ethash.DatasetDir, config.Ethash.DatasetsInMem, config.Ethash.DatasetsOnDisk) CacheDir: ctx.ResolvePath(config.CacheDir),
CachesInMem: config.CachesInMem,
CachesOnDisk: config.CachesOnDisk,
DatasetDir: config.DatasetDir,
DatasetsInMem: config.DatasetsInMem,
DatasetsOnDisk: config.DatasetsOnDisk,
})
engine.SetThreads(-1) // Disable CPU mining engine.SetThreads(-1) // Disable CPU mining
return engine return engine
} }

View file

@ -35,7 +35,7 @@ import (
// DefaultConfig contains default settings for use on the Ethereum main net. // DefaultConfig contains default settings for use on the Ethereum main net.
var DefaultConfig = Config{ var DefaultConfig = Config{
SyncMode: downloader.FastSync, SyncMode: downloader.FastSync,
Ethash: ethash.EthashConfig{ Ethash: ethash.Config{
CacheDir: "ethash", CacheDir: "ethash",
CachesInMem: 2, CachesInMem: 2,
CachesOnDisk: 3, CachesOnDisk: 3,
@ -95,7 +95,7 @@ type Config struct {
GasPrice *big.Int GasPrice *big.Int
// Ethash options // Ethash options
Ethash ethash.EthashConfig Ethash ethash.Config
// Transaction pool options // Transaction pool options
TxPool core.TxPoolConfig TxPool core.TxPoolConfig

View file

@ -64,9 +64,9 @@ func (c Config) MarshalTOML() (interface{}, error) {
enc.GPO = c.GPO enc.GPO = c.GPO
enc.EnablePreimageRecording = c.EnablePreimageRecording enc.EnablePreimageRecording = c.EnablePreimageRecording
enc.DocRoot = c.DocRoot enc.DocRoot = c.DocRoot
enc.PowFake = c.Ethash.PowFake enc.PowFake = c.Ethash.Fake
enc.PowTest = c.Ethash.PowTest enc.PowTest = c.Ethash.Test
enc.PowShared = c.Ethash.PowShared enc.PowShared = c.Ethash.Shared
return &enc, nil return &enc, nil
} }
@ -170,13 +170,13 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error {
c.DocRoot = *dec.DocRoot c.DocRoot = *dec.DocRoot
} }
if dec.PowFake != nil { if dec.PowFake != nil {
c.Ethash.PowFake = *dec.PowFake c.Ethash.Fake = *dec.PowFake
} }
if dec.PowTest != nil { if dec.PowTest != nil {
c.Ethash.PowTest = *dec.PowTest c.Ethash.Test = *dec.PowTest
} }
if dec.PowShared != nil { if dec.PowShared != nil {
c.Ethash.PowShared = *dec.PowShared c.Ethash.Shared = *dec.PowShared
} }
return nil return nil
} }

View file

@ -98,7 +98,7 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
peers: peers, peers: peers,
reqDist: newRequestDistributor(peers, quitSync), reqDist: newRequestDistributor(peers, quitSync),
accountManager: ctx.AccountManager, accountManager: ctx.AccountManager,
engine: eth.CreateConsensusEngine(ctx, config, chainConfig, chainDb), engine: eth.CreateConsensusEngine(ctx, &config.Ethash, chainConfig, chainDb),
shutdownChan: make(chan bool), shutdownChan: make(chan bool),
networkId: config.NetworkId, networkId: config.NetworkId,
bloomRequests: make(chan chan *bloombits.Retrieval), bloomRequests: make(chan chan *bloombits.Retrieval),