From 30d706c35e16305e2e3ec0eb6a6bdd6aba50d9d2 Mon Sep 17 00:00:00 2001 From: Felix Lange Date: Wed, 12 Apr 2017 16:27:23 +0200 Subject: cmd/geth: add --config file flag (#13875) * p2p/discover, p2p/discv5: add marshaling methods to Node * p2p/netutil: make Netlist decodable from TOML * common/math: encode nil HexOrDecimal256 as 0x0 * cmd/geth: add --config file flag * cmd/geth: add missing license header * eth: prettify Config again, fix tests * eth: use gasprice.Config instead of duplicating its fields * eth/gasprice: hide nil default from dumpconfig output * cmd/geth: hide genesis block in dumpconfig output * node: make tests compile * console: fix tests * cmd/geth: make TOML keys look exactly like Go struct fields * p2p: use discovery by default This makes the zero Config slightly more useful. It also fixes package node tests because Node detects reuse of the datadir through the NodeDatabase. * cmd/geth: make ethstats URL settable through config file * cmd/faucet: fix configuration * cmd/geth: dedup attach tests * eth: add comment for DefaultConfig * eth: pass downloader.SyncMode in Config This removes the FastSync, LightSync flags in favour of a more general SyncMode flag. * cmd/utils: remove jitvm flags * cmd/utils: make mutually exclusive flag error prettier It now reads: Fatal: flags --dev, --testnet can't be used at the same time * p2p: fix typo * node: add DefaultConfig, use it for geth * mobile: add missing NoDiscovery option * cmd/utils: drop MakeNode This exposed a couple of places that needed to be updated to use node.DefaultConfig. * node: fix typo * eth: make fast sync the default mode * cmd/utils: remove IPCApiFlag (unused) * node: remove default IPC path Set it in the frontends instead. * cmd/geth: add --syncmode * cmd/utils: make --ipcdisable and --ipcpath mutually exclusive * cmd/utils: don't enable WS, HTTP when setting addr * cmd/utils: fix --identity --- eth/backend.go | 92 +++++++++-------------- eth/config.go | 117 +++++++++++++++++++++++++++++ eth/downloader/modes.go | 33 +++++++++ eth/gasprice/gasprice.go | 2 +- eth/gen_config.go | 186 +++++++++++++++++++++++++++++++++++++++++++++++ eth/handler.go | 12 +-- eth/handler_test.go | 18 ++--- eth/helper_test.go | 11 +-- eth/protocol.go | 5 +- eth/protocol_test.go | 11 +-- eth/sync_test.go | 5 +- 11 files changed, 401 insertions(+), 91 deletions(-) create mode 100644 eth/config.go create mode 100644 eth/gen_config.go (limited to 'eth') diff --git a/eth/backend.go b/eth/backend.go index 4dffa2990..7ee591f9e 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -18,14 +18,15 @@ package eth import ( + "errors" "fmt" - "math/big" - "regexp" + "runtime" "sync" "sync/atomic" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/consensus/ethash" @@ -43,55 +44,10 @@ import ( "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rpc" ) -var ( - datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true} - portInUseErrRE = regexp.MustCompile("address already in use") -) - -type Config struct { - // The genesis block, which is inserted if the database is empty. - // If nil, the Ethereum main net block is used. - Genesis *core.Genesis - - NetworkId int // Network ID to use for selecting peers to connect to - - FastSync bool // Enables the state download based fast synchronisation algorithm - LightMode bool // Running in light client mode - LightServ int // Maximum percentage of time allowed for serving LES requests - LightPeers int // Maximum number of LES client peers - MaxPeers int // Maximum number of global peers - - SkipBcVersionCheck bool // e.g. blockchain export - DatabaseCache int - DatabaseHandles int - - DocRoot string - PowFake bool - PowTest bool - PowShared bool - ExtraData []byte - - EthashCacheDir string - EthashCachesInMem int - EthashCachesOnDisk int - EthashDatasetDir string - EthashDatasetsInMem int - EthashDatasetsOnDisk int - - Etherbase common.Address - GasPrice *big.Int - MinerThreads int - SolcPath string - - GpoBlocks int - GpoPercentile int - - EnablePreimageRecording bool -} - type LesServer interface { Start(srvr *p2p.Server) Stop() @@ -137,6 +93,13 @@ func (s *Ethereum) AddLesServer(ls LesServer) { // New creates a new Ethereum object (including the // initialisation of the common Ethereum object) func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { + if config.SyncMode == downloader.LightSync { + return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum") + } + if !config.SyncMode.IsValid() { + return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode) + } + chainDb, err := CreateDB(ctx, config, "chaindata") if err != nil { return nil, err @@ -201,25 +164,41 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { } } - if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil { + if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil { return nil, err } eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine) eth.miner.SetGasPrice(config.GasPrice) - eth.miner.SetExtra(config.ExtraData) + eth.miner.SetExtra(makeExtraData(config.ExtraData)) eth.ApiBackend = &EthApiBackend{eth, nil} - gpoParams := gasprice.Config{ - Blocks: config.GpoBlocks, - Percentile: config.GpoPercentile, - Default: config.GasPrice, + gpoParams := config.GPO + if gpoParams.Default == nil { + gpoParams.Default = config.GasPrice } eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams) return eth, nil } +func makeExtraData(extra []byte) []byte { + if len(extra) == 0 { + // create default extradata + extra, _ = rlp.EncodeToBytes([]interface{}{ + uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), + "geth", + runtime.Version(), + runtime.GOOS, + }) + } + if uint64(len(extra)) > params.MaximumExtraDataSize { + log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize) + extra = nil + } + return extra +} + // CreateDB creates the chain database. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) { db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles) @@ -415,8 +394,3 @@ func (s *Ethereum) Stop() error { return nil } - -// This function will wait for a shutdown and resumes main thread execution -func (s *Ethereum) WaitForShutdown() { - <-s.shutdownChan -} diff --git a/eth/config.go b/eth/config.go new file mode 100644 index 000000000..9c3f8b0fb --- /dev/null +++ b/eth/config.go @@ -0,0 +1,117 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package eth + +import ( + "math/big" + "os" + "os/user" + "path/filepath" + "runtime" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/eth/downloader" + "github.com/ethereum/go-ethereum/eth/gasprice" + "github.com/ethereum/go-ethereum/params" +) + +// DefaultConfig contains default settings for use on the Ethereum main net. +var DefaultConfig = Config{ + SyncMode: downloader.FastSync, + EthashCachesInMem: 2, + EthashCachesOnDisk: 3, + EthashDatasetsInMem: 1, + EthashDatasetsOnDisk: 2, + NetworkId: 1, + LightPeers: 20, + DatabaseCache: 128, + GasPrice: big.NewInt(20 * params.Shannon), + + GPO: gasprice.Config{ + Blocks: 10, + Percentile: 50, + }, +} + +func init() { + home := os.Getenv("HOME") + if home == "" { + if user, err := user.Current(); err == nil { + home = user.HomeDir + } + } + if runtime.GOOS == "windows" { + DefaultConfig.EthashDatasetDir = filepath.Join(home, "AppData", "Ethash") + } else { + DefaultConfig.EthashDatasetDir = filepath.Join(home, ".ethash") + } +} + +//go:generate gencodec -type Config -field-override configMarshaling -formats toml -out gen_config.go + +type Config struct { + // The genesis block, which is inserted if the database is empty. + // If nil, the Ethereum main net block is used. + Genesis *core.Genesis `toml:",omitempty"` + + // Protocol options + NetworkId int // Network ID to use for selecting peers to connect to + SyncMode downloader.SyncMode + + // Light client options + LightServ int `toml:",omitempty"` // Maximum percentage of time allowed for serving LES requests + LightPeers int `toml:",omitempty"` // Maximum number of LES client peers + MaxPeers int `toml:"-"` // Maximum number of global peers + + // Database options + SkipBcVersionCheck bool `toml:"-"` + DatabaseHandles int `toml:"-"` + DatabaseCache int + + // Mining-related options + Etherbase common.Address `toml:",omitempty"` + MinerThreads int `toml:",omitempty"` + ExtraData []byte `toml:",omitempty"` + GasPrice *big.Int + + // Ethash options + EthashCacheDir string + EthashCachesInMem int + EthashCachesOnDisk int + EthashDatasetDir string + EthashDatasetsInMem int + EthashDatasetsOnDisk int + + // Gas Price Oracle options + GPO gasprice.Config + + // Enables tracking of SHA3 preimages in the VM + EnablePreimageRecording bool + + // Miscellaneous options + SolcPath string + DocRoot string `toml:"-"` + PowFake bool `toml:"-"` + PowTest bool `toml:"-"` + PowShared bool `toml:"-"` +} + +type configMarshaling struct { + ExtraData hexutil.Bytes +} diff --git a/eth/downloader/modes.go b/eth/downloader/modes.go index ae3c43888..8ecdf91f1 100644 --- a/eth/downloader/modes.go +++ b/eth/downloader/modes.go @@ -16,6 +16,8 @@ package downloader +import "fmt" + // SyncMode represents the synchronisation mode of the downloader. type SyncMode int @@ -25,6 +27,10 @@ const ( LightSync // Download only the headers and terminate afterwards ) +func (mode SyncMode) IsValid() bool { + return mode >= FullSync && mode <= LightSync +} + // String implements the stringer interface. func (mode SyncMode) String() string { switch mode { @@ -38,3 +44,30 @@ func (mode SyncMode) String() string { return "unknown" } } + +func (mode SyncMode) MarshalText() ([]byte, error) { + switch mode { + case FullSync: + return []byte("full"), nil + case FastSync: + return []byte("fast"), nil + case LightSync: + return []byte("light"), nil + default: + return nil, fmt.Errorf("unknown sync mode %d", mode) + } +} + +func (mode *SyncMode) UnmarshalText(text []byte) error { + switch string(text) { + case "full": + *mode = FullSync + case "fast": + *mode = FastSync + case "light": + *mode = LightSync + default: + return fmt.Errorf(`unknown sync mode %q, want "full", "fast" or "light"`, text) + } + return nil +} diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index bac048c88..05c25e644 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -33,7 +33,7 @@ var maxPrice = big.NewInt(500 * params.Shannon) type Config struct { Blocks int Percentile int - Default *big.Int + Default *big.Int `toml:",omitempty"` } // Oracle recommends gas prices based on the content of recent diff --git a/eth/gen_config.go b/eth/gen_config.go new file mode 100644 index 000000000..d34273e1c --- /dev/null +++ b/eth/gen_config.go @@ -0,0 +1,186 @@ +// Code generated by github.com/fjl/gencodec. DO NOT EDIT. + +package eth + +import ( + "math/big" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/eth/downloader" + "github.com/ethereum/go-ethereum/eth/gasprice" +) + +func (c Config) MarshalTOML() (interface{}, error) { + type Config struct { + Genesis *core.Genesis `toml:",omitempty"` + NetworkId int + SyncMode downloader.SyncMode + LightServ int `toml:",omitempty"` + LightPeers int `toml:",omitempty"` + MaxPeers int `toml:"-"` + SkipBcVersionCheck bool `toml:"-"` + DatabaseHandles int `toml:"-"` + DatabaseCache int + Etherbase common.Address `toml:",omitempty"` + MinerThreads int `toml:",omitempty"` + ExtraData hexutil.Bytes `toml:",omitempty"` + GasPrice *big.Int + EthashCacheDir string + EthashCachesInMem int + EthashCachesOnDisk int + EthashDatasetDir string + EthashDatasetsInMem int + EthashDatasetsOnDisk int + GPO gasprice.Config + EnablePreimageRecording bool + SolcPath string + DocRoot string `toml:"-"` + PowFake bool `toml:"-"` + PowTest bool `toml:"-"` + PowShared bool `toml:"-"` + } + var enc Config + enc.Genesis = c.Genesis + enc.NetworkId = c.NetworkId + enc.SyncMode = c.SyncMode + enc.LightServ = c.LightServ + enc.LightPeers = c.LightPeers + enc.MaxPeers = c.MaxPeers + enc.SkipBcVersionCheck = c.SkipBcVersionCheck + enc.DatabaseHandles = c.DatabaseHandles + enc.DatabaseCache = c.DatabaseCache + enc.Etherbase = c.Etherbase + enc.MinerThreads = c.MinerThreads + enc.ExtraData = c.ExtraData + enc.GasPrice = c.GasPrice + enc.EthashCacheDir = c.EthashCacheDir + enc.EthashCachesInMem = c.EthashCachesInMem + enc.EthashCachesOnDisk = c.EthashCachesOnDisk + enc.EthashDatasetDir = c.EthashDatasetDir + enc.EthashDatasetsInMem = c.EthashDatasetsInMem + enc.EthashDatasetsOnDisk = c.EthashDatasetsOnDisk + enc.GPO = c.GPO + enc.EnablePreimageRecording = c.EnablePreimageRecording + enc.SolcPath = c.SolcPath + enc.DocRoot = c.DocRoot + enc.PowFake = c.PowFake + enc.PowTest = c.PowTest + enc.PowShared = c.PowShared + return &enc, nil +} + +func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { + type Config struct { + Genesis *core.Genesis `toml:",omitempty"` + NetworkId *int + SyncMode *downloader.SyncMode + LightServ *int `toml:",omitempty"` + LightPeers *int `toml:",omitempty"` + MaxPeers *int `toml:"-"` + SkipBcVersionCheck *bool `toml:"-"` + DatabaseHandles *int `toml:"-"` + DatabaseCache *int + Etherbase *common.Address `toml:",omitempty"` + MinerThreads *int `toml:",omitempty"` + ExtraData hexutil.Bytes `toml:",omitempty"` + GasPrice *big.Int + EthashCacheDir *string + EthashCachesInMem *int + EthashCachesOnDisk *int + EthashDatasetDir *string + EthashDatasetsInMem *int + EthashDatasetsOnDisk *int + GPO *gasprice.Config + EnablePreimageRecording *bool + SolcPath *string + DocRoot *string `toml:"-"` + PowFake *bool `toml:"-"` + PowTest *bool `toml:"-"` + PowShared *bool `toml:"-"` + } + var dec Config + if err := unmarshal(&dec); err != nil { + return err + } + if dec.Genesis != nil { + c.Genesis = dec.Genesis + } + if dec.NetworkId != nil { + c.NetworkId = *dec.NetworkId + } + if dec.SyncMode != nil { + c.SyncMode = *dec.SyncMode + } + if dec.LightServ != nil { + c.LightServ = *dec.LightServ + } + if dec.LightPeers != nil { + c.LightPeers = *dec.LightPeers + } + if dec.MaxPeers != nil { + c.MaxPeers = *dec.MaxPeers + } + if dec.SkipBcVersionCheck != nil { + c.SkipBcVersionCheck = *dec.SkipBcVersionCheck + } + if dec.DatabaseHandles != nil { + c.DatabaseHandles = *dec.DatabaseHandles + } + if dec.DatabaseCache != nil { + c.DatabaseCache = *dec.DatabaseCache + } + if dec.Etherbase != nil { + c.Etherbase = *dec.Etherbase + } + if dec.MinerThreads != nil { + c.MinerThreads = *dec.MinerThreads + } + if dec.ExtraData != nil { + c.ExtraData = dec.ExtraData + } + if dec.GasPrice != nil { + c.GasPrice = dec.GasPrice + } + if dec.EthashCacheDir != nil { + c.EthashCacheDir = *dec.EthashCacheDir + } + if dec.EthashCachesInMem != nil { + c.EthashCachesInMem = *dec.EthashCachesInMem + } + if dec.EthashCachesOnDisk != nil { + c.EthashCachesOnDisk = *dec.EthashCachesOnDisk + } + if dec.EthashDatasetDir != nil { + c.EthashDatasetDir = *dec.EthashDatasetDir + } + if dec.EthashDatasetsInMem != nil { + c.EthashDatasetsInMem = *dec.EthashDatasetsInMem + } + if dec.EthashDatasetsOnDisk != nil { + c.EthashDatasetsOnDisk = *dec.EthashDatasetsOnDisk + } + if dec.GPO != nil { + c.GPO = *dec.GPO + } + if dec.EnablePreimageRecording != nil { + c.EnablePreimageRecording = *dec.EnablePreimageRecording + } + if dec.SolcPath != nil { + c.SolcPath = *dec.SolcPath + } + if dec.DocRoot != nil { + c.DocRoot = *dec.DocRoot + } + if dec.PowFake != nil { + c.PowFake = *dec.PowFake + } + if dec.PowTest != nil { + c.PowTest = *dec.PowTest + } + if dec.PowShared != nil { + c.PowShared = *dec.PowShared + } + return nil +} diff --git a/eth/handler.go b/eth/handler.go index 99c2c4b32..fb8a0fd57 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -96,7 +96,7 @@ type ProtocolManager struct { // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable // with the ethereum network. -func NewProtocolManager(config *params.ChainConfig, fastSync bool, networkId int, maxPeers int, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) { +func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkId int, maxPeers int, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) { // Create the protocol manager with the base fields manager := &ProtocolManager{ networkId: networkId, @@ -113,18 +113,18 @@ func NewProtocolManager(config *params.ChainConfig, fastSync bool, networkId int quitSync: make(chan struct{}), } // Figure out whether to allow fast sync or not - if fastSync && blockchain.CurrentBlock().NumberU64() > 0 { + if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 { log.Warn("Blockchain not empty, fast sync disabled") - fastSync = false + mode = downloader.FullSync } - if fastSync { + if mode == downloader.FastSync { manager.fastSync = uint32(1) } // Initiate a sub-protocol for every implemented version we can handle manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions)) for i, version := range ProtocolVersions { // Skip protocol version if incompatible with the mode of operation - if fastSync && version < eth63 { + if mode == downloader.FastSync && version < eth63 { continue } // Compatible; initialise the sub-protocol @@ -159,7 +159,7 @@ func NewProtocolManager(config *params.ChainConfig, fastSync bool, networkId int return nil, errIncompatibleConfig } // Construct the different synchronisation mechanisms - manager.downloader = downloader.New(downloader.FullSync, chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeaderByHash, + manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeaderByHash, blockchain.GetBlockByHash, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead, blockchain.GetTdByHash, blockchain.InsertHeaderChain, manager.blockchain.InsertChain, blockchain.InsertReceiptChain, blockchain.Rollback, manager.removePeer) diff --git a/eth/handler_test.go b/eth/handler_test.go index f85d730b6..413ed2bff 100644 --- a/eth/handler_test.go +++ b/eth/handler_test.go @@ -44,11 +44,11 @@ func TestProtocolCompatibility(t *testing.T) { // Define the compatibility chart tests := []struct { version uint - fastSync bool + mode downloader.SyncMode compatible bool }{ - {61, false, true}, {62, false, true}, {63, false, true}, - {61, true, false}, {62, true, false}, {63, true, true}, + {61, downloader.FullSync, true}, {62, downloader.FullSync, true}, {63, downloader.FullSync, true}, + {61, downloader.FastSync, false}, {62, downloader.FastSync, false}, {63, downloader.FastSync, true}, } // Make sure anything we screw up is restored backup := ProtocolVersions @@ -58,7 +58,7 @@ func TestProtocolCompatibility(t *testing.T) { for i, tt := range tests { ProtocolVersions = []uint{tt.version} - pm, err := newTestProtocolManager(tt.fastSync, 0, nil, nil) + pm, err := newTestProtocolManager(tt.mode, 0, nil, nil) if pm != nil { defer pm.Stop() } @@ -73,7 +73,7 @@ func TestGetBlockHeaders62(t *testing.T) { testGetBlockHeaders(t, 62) } func TestGetBlockHeaders63(t *testing.T) { testGetBlockHeaders(t, 63) } func testGetBlockHeaders(t *testing.T, protocol int) { - pm := newTestProtocolManagerMust(t, false, downloader.MaxHashFetch+15, nil, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, downloader.MaxHashFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() @@ -232,7 +232,7 @@ func TestGetBlockBodies62(t *testing.T) { testGetBlockBodies(t, 62) } func TestGetBlockBodies63(t *testing.T) { testGetBlockBodies(t, 63) } func testGetBlockBodies(t *testing.T, protocol int) { - pm := newTestProtocolManagerMust(t, false, downloader.MaxBlockFetch+15, nil, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, downloader.MaxBlockFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() @@ -339,7 +339,7 @@ func testGetNodeData(t *testing.T, protocol int) { } } // Assemble the test environment - pm := newTestProtocolManagerMust(t, false, 4, generator, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() @@ -431,7 +431,7 @@ func testGetReceipt(t *testing.T, protocol int) { } } // Assemble the test environment - pm := newTestProtocolManagerMust(t, false, 4, generator, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() @@ -476,7 +476,7 @@ func testDAOChallenge(t *testing.T, localForked, remoteForked bool, timeout bool genesis = gspec.MustCommit(db) blockchain, _ = core.NewBlockChain(db, config, pow, evmux, vm.Config{}) ) - pm, err := NewProtocolManager(config, false, NetworkId, 1000, evmux, new(testTxPool), pow, blockchain, db) + pm, err := NewProtocolManager(config, downloader.FullSync, DefaultConfig.NetworkId, 1000, evmux, new(testTxPool), pow, blockchain, db) if err != nil { t.Fatalf("failed to start test protocol manager: %v", err) } diff --git a/eth/helper_test.go b/eth/helper_test.go index a8c538e6c..21ac3724e 100644 --- a/eth/helper_test.go +++ b/eth/helper_test.go @@ -33,6 +33,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/p2p" @@ -48,7 +49,7 @@ var ( // newTestProtocolManager creates a new protocol manager for testing purposes, // with the given number of blocks already known, and potential notification // channels for different events. -func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, error) { +func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, error) { var ( evmux = new(event.TypeMux) engine = ethash.NewFaker() @@ -65,7 +66,7 @@ func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core panic(err) } - pm, err := NewProtocolManager(gspec.Config, fastSync, NetworkId, 1000, evmux, &testTxPool{added: newtx}, engine, blockchain, db) + pm, err := NewProtocolManager(gspec.Config, mode, DefaultConfig.NetworkId, 1000, evmux, &testTxPool{added: newtx}, engine, blockchain, db) if err != nil { return nil, err } @@ -77,8 +78,8 @@ func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core // with the given number of blocks already known, and potential notification // channels for different events. In case of an error, the constructor force- // fails the test. -func newTestProtocolManagerMust(t *testing.T, fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager { - pm, err := newTestProtocolManager(fastSync, blocks, generator, newtx) +func newTestProtocolManagerMust(t *testing.T, mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager { + pm, err := newTestProtocolManager(mode, blocks, generator, newtx) if err != nil { t.Fatalf("Failed to create protocol manager: %v", err) } @@ -172,7 +173,7 @@ func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*te func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) { msg := &statusData{ ProtocolVersion: uint32(p.version), - NetworkId: uint32(NetworkId), + NetworkId: uint32(DefaultConfig.NetworkId), TD: td, CurrentBlock: head, GenesisBlock: genesis, diff --git a/eth/protocol.go b/eth/protocol.go index 7d22b33de..40997da7a 100644 --- a/eth/protocol.go +++ b/eth/protocol.go @@ -41,10 +41,7 @@ var ProtocolVersions = []uint{eth63, eth62} // Number of implemented message corresponding to different protocol versions. var ProtocolLengths = []uint64{17, 8} -const ( - NetworkId = 1 - ProtocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message -) +const ProtocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message // eth protocol message codes const ( diff --git a/eth/protocol_test.go b/eth/protocol_test.go index 3c9a734df..74180bedd 100644 --- a/eth/protocol_test.go +++ b/eth/protocol_test.go @@ -25,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rlp" ) @@ -40,7 +41,7 @@ func TestStatusMsgErrors62(t *testing.T) { testStatusMsgErrors(t, 62) } func TestStatusMsgErrors63(t *testing.T) { testStatusMsgErrors(t, 63) } func testStatusMsgErrors(t *testing.T, protocol int) { - pm := newTestProtocolManagerMust(t, false, 0, nil, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil) td, currentBlock, genesis := pm.blockchain.Status() defer pm.Stop() @@ -54,7 +55,7 @@ func testStatusMsgErrors(t *testing.T, protocol int) { wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"), }, { - code: StatusMsg, data: statusData{10, NetworkId, td, currentBlock, genesis}, + code: StatusMsg, data: statusData{10, uint32(DefaultConfig.NetworkId), td, currentBlock, genesis}, wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", protocol), }, { @@ -62,7 +63,7 @@ func testStatusMsgErrors(t *testing.T, protocol int) { wantError: errResp(ErrNetworkIdMismatch, "999 (!= 1)"), }, { - code: StatusMsg, data: statusData{uint32(protocol), NetworkId, td, currentBlock, common.Hash{3}}, + code: StatusMsg, data: statusData{uint32(protocol), uint32(DefaultConfig.NetworkId), td, currentBlock, common.Hash{3}}, wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000 (!= %x)", genesis[:8]), }, } @@ -93,7 +94,7 @@ func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) } func testRecvTransactions(t *testing.T, protocol int) { txAdded := make(chan []*types.Transaction) - pm := newTestProtocolManagerMust(t, false, 0, nil, txAdded) + pm := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, txAdded) pm.acceptTxs = 1 // mark synced to accept transactions p, _ := newTestPeer("peer", protocol, pm, true) defer pm.Stop() @@ -120,7 +121,7 @@ func TestSendTransactions62(t *testing.T) { testSendTransactions(t, 62) } func TestSendTransactions63(t *testing.T) { testSendTransactions(t, 63) } func testSendTransactions(t *testing.T, protocol int) { - pm := newTestProtocolManagerMust(t, false, 0, nil, nil) + pm := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil) defer pm.Stop() // Fill the pool with big transactions. diff --git a/eth/sync_test.go b/eth/sync_test.go index 198ffaf27..9eaa1156f 100644 --- a/eth/sync_test.go +++ b/eth/sync_test.go @@ -21,6 +21,7 @@ import ( "testing" "time" + "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/discover" ) @@ -29,12 +30,12 @@ import ( // imported into the blockchain. func TestFastSyncDisabling(t *testing.T) { // Create a pristine protocol manager, check that fast sync is left enabled - pmEmpty := newTestProtocolManagerMust(t, true, 0, nil, nil) + pmEmpty := newTestProtocolManagerMust(t, downloader.FastSync, 0, nil, nil) if atomic.LoadUint32(&pmEmpty.fastSync) == 0 { t.Fatalf("fast sync disabled on pristine blockchain") } // Create a full protocol manager, check that fast sync gets disabled - pmFull := newTestProtocolManagerMust(t, true, 1024, nil, nil) + pmFull := newTestProtocolManagerMust(t, downloader.FastSync, 1024, nil, nil) if atomic.LoadUint32(&pmFull.fastSync) == 1 { t.Fatalf("fast sync not disabled on non-empty blockchain") } -- cgit