diff --git a/cmd/geth/dao_test.go b/cmd/geth/dao_test.go
new file mode 100644
index 0000000000..bfa0c2a035
--- /dev/null
+++ b/cmd/geth/dao_test.go
@@ -0,0 +1,232 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "io/ioutil"
+ "math/big"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/params"
+)
+
+// Genesis block for nodes which don't care about the DAO fork (i.e. not configured)
+var daoOldGenesis = `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00",
+ "config" : {}
+}`
+
+// Genesis block for nodes which actively oppose the DAO fork
+var daoNoForkGenesis = `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00",
+ "config" : {
+ "daoForkBlock" : 314,
+ "daoForkSupport" : false
+ }
+}`
+
+// Genesis block for nodes which actively support the DAO fork
+var daoProForkGenesis = `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00",
+ "config" : {
+ "daoForkBlock" : 314,
+ "daoForkSupport" : true
+ }
+}`
+
+var daoGenesisHash = common.HexToHash("5e1fc79cb4ffa4739177b5408045cd5d51c6cf766133f23f7cd72ee1f8d790e0")
+var daoGenesisForkBlock = big.NewInt(314)
+
+// Tests that the DAO hard-fork number and the nodes support/opposition is correctly
+// set in the database after various initialization procedures and invocations.
+func TestDAODefaultMainnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, "", [][2]bool{{false, false}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAOSupportMainnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, "", [][2]bool{{true, false}}, params.MainNetDAOForkBlock, true)
+}
+func TestDAOOpposeMainnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, "", [][2]bool{{false, true}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAOSwitchToSupportMainnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, "", [][2]bool{{false, true}, {true, false}}, params.MainNetDAOForkBlock, true)
+}
+func TestDAOSwitchToOpposeMainnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, "", [][2]bool{{true, false}, {false, true}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAODefaultTestnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, true, "", [][2]bool{{false, false}}, params.TestNetDAOForkBlock, false)
+}
+func TestDAOSupportTestnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, true, "", [][2]bool{{true, false}}, params.TestNetDAOForkBlock, true)
+}
+func TestDAOOpposeTestnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, true, "", [][2]bool{{false, true}}, params.TestNetDAOForkBlock, false)
+}
+func TestDAOSwitchToSupportTestnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, true, "", [][2]bool{{false, true}, {true, false}}, params.TestNetDAOForkBlock, true)
+}
+func TestDAOSwitchToOpposeTestnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, true, "", [][2]bool{{true, false}, {false, true}}, params.TestNetDAOForkBlock, false)
+}
+func TestDAOInitOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{}, nil, false)
+}
+func TestDAODefaultOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{{false, false}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAOSupportOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{{true, false}}, params.MainNetDAOForkBlock, true)
+}
+func TestDAOOpposeOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{{false, true}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAOSwitchToSupportOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{{false, true}, {true, false}}, params.MainNetDAOForkBlock, true)
+}
+func TestDAOSwitchToOpposeOldPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoOldGenesis, [][2]bool{{true, false}, {false, true}}, params.MainNetDAOForkBlock, false)
+}
+func TestDAOInitNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{}, daoGenesisForkBlock, false)
+}
+func TestDAODefaultNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{{false, false}}, daoGenesisForkBlock, false)
+}
+func TestDAOSupportNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{{true, false}}, daoGenesisForkBlock, true)
+}
+func TestDAOOpposeNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{{false, true}}, daoGenesisForkBlock, false)
+}
+func TestDAOSwitchToSupportNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{{false, true}, {true, false}}, daoGenesisForkBlock, true)
+}
+func TestDAOSwitchToOpposeNoForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoNoForkGenesis, [][2]bool{{true, false}, {false, true}}, daoGenesisForkBlock, false)
+}
+func TestDAOInitProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{}, daoGenesisForkBlock, true)
+}
+func TestDAODefaultProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{{false, false}}, daoGenesisForkBlock, true)
+}
+func TestDAOSupportProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{{true, false}}, daoGenesisForkBlock, true)
+}
+func TestDAOOpposeProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{{false, true}}, daoGenesisForkBlock, false)
+}
+func TestDAOSwitchToSupportProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{{false, true}, {true, false}}, daoGenesisForkBlock, true)
+}
+func TestDAOSwitchToOpposeProForkPrivnet(t *testing.T) {
+ testDAOForkBlockNewChain(t, false, daoProForkGenesis, [][2]bool{{true, false}, {false, true}}, daoGenesisForkBlock, false)
+}
+
+func testDAOForkBlockNewChain(t *testing.T, testnet bool, genesis string, votes [][2]bool, expectBlock *big.Int, expectVote bool) {
+ // Create a temporary data directory to use and inspect later
+ datadir := tmpdir(t)
+ defer os.RemoveAll(datadir)
+
+ // Start a Geth instance with the requested flags set and immediately terminate
+ if genesis != "" {
+ json := filepath.Join(datadir, "genesis.json")
+ if err := ioutil.WriteFile(json, []byte(genesis), 0600); err != nil {
+ t.Fatalf("failed to write genesis file: %v", err)
+ }
+ runGeth(t, "--datadir", datadir, "init", json).cmd.Wait()
+ }
+ for _, vote := range votes {
+ args := []string{"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable", "--datadir", datadir}
+ if testnet {
+ args = append(args, "--testnet")
+ }
+ if vote[0] {
+ args = append(args, "--support-dao-fork")
+ }
+ if vote[1] {
+ args = append(args, "--oppose-dao-fork")
+ }
+ geth := runGeth(t, append(args, []string{"--exec", "2+2", "console"}...)...)
+ geth.cmd.Wait()
+ }
+ // Retrieve the DAO config flag from the database
+ path := filepath.Join(datadir, "chaindata")
+ if testnet && genesis == "" {
+ path = filepath.Join(datadir, "testnet", "chaindata")
+ }
+ db, err := ethdb.NewLDBDatabase(path, 0, 0)
+ if err != nil {
+ t.Fatalf("failed to open test database: %v", err)
+ }
+ defer db.Close()
+
+ genesisHash := common.HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3")
+ if testnet {
+ genesisHash = common.HexToHash("0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303")
+ }
+ if genesis != "" {
+ genesisHash = daoGenesisHash
+ }
+ config, err := core.GetChainConfig(db, genesisHash)
+ if err != nil {
+ t.Fatalf("failed to retrieve chain config: %v", err)
+ }
+ // Validate the DAO hard-fork block number against the expected value
+ if config.DAOForkBlock == nil {
+ if expectBlock != nil {
+ t.Errorf("dao hard-fork block mismatch: have nil, want %v", expectBlock)
+ }
+ } else if expectBlock == nil {
+ t.Errorf("dao hard-fork block mismatch: have %v, want nil", config.DAOForkBlock)
+ } else if config.DAOForkBlock.Cmp(expectBlock) != 0 {
+ t.Errorf("dao hard-fork block mismatch: have %v, want %v", config.DAOForkBlock, expectBlock)
+ }
+ if config.DAOForkSupport != expectVote {
+ t.Errorf("dao hard-fork support mismatch: have %v, want %v", config.DAOForkSupport, expectVote)
+ }
+}
diff --git a/cmd/geth/genesis_test.go b/cmd/geth/genesis_test.go
new file mode 100644
index 0000000000..4f8b1642ef
--- /dev/null
+++ b/cmd/geth/genesis_test.go
@@ -0,0 +1,107 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+var customGenesisTests = []struct {
+ genesis string
+ query string
+ result string
+}{
+ // Plain genesis file without anything extra
+ {
+ genesis: `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00"
+ }`,
+ query: "eth.getBlock(0).nonce",
+ result: "0x0000000000000042",
+ },
+ // Genesis file with an empty chain configuration (ensure missing fields work)
+ {
+ genesis: `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00",
+ "config" : {}
+ }`,
+ query: "eth.getBlock(0).nonce",
+ result: "0x0000000000000042",
+ },
+ // Genesis file with specific chain configurations
+ {
+ genesis: `{
+ "alloc" : {},
+ "coinbase" : "0x0000000000000000000000000000000000000000",
+ "difficulty" : "0x20000",
+ "extraData" : "",
+ "gasLimit" : "0x2fefd8",
+ "nonce" : "0x0000000000000042",
+ "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "timestamp" : "0x00",
+ "config" : {
+ "homesteadBlock" : 314,
+ "daoForkBlock" : 141,
+ "daoForkSupport" : true
+ },
+ }`,
+ query: "eth.getBlock(0).nonce",
+ result: "0x0000000000000042",
+ },
+}
+
+// Tests that initializing Geth with a custom genesis block and chain definitions
+// work properly.
+func TestCustomGenesis(t *testing.T) {
+ for i, tt := range customGenesisTests {
+ // Create a temporary data directory to use and inspect later
+ datadir := tmpdir(t)
+ defer os.RemoveAll(datadir)
+
+ // Initialize the data directory with the custom genesis block
+ json := filepath.Join(datadir, "genesis.json")
+ if err := ioutil.WriteFile(json, []byte(tt.genesis), 0600); err != nil {
+ t.Fatalf("test %d: failed to write genesis file: %v", i, err)
+ }
+ runGeth(t, "--datadir", datadir, "init", json).cmd.Wait()
+
+ // Query the custom genesis block
+ geth := runGeth(t, "--datadir", datadir, "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable", "--exec", tt.query, "console")
+ geth.expectRegexp(tt.result)
+ geth.expectExit()
+ }
+}
diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index cb43f8769d..5f1157b90b 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -150,7 +150,6 @@ participating.
utils.IdentityFlag,
utils.UnlockedAccountFlag,
utils.PasswordFileFlag,
- utils.GenesisFileFlag,
utils.BootnodesFlag,
utils.DataDirFlag,
utils.KeyStoreDirFlag,
@@ -165,6 +164,8 @@ participating.
utils.MaxPendingPeersFlag,
utils.EtherbaseFlag,
utils.GasPriceFlag,
+ utils.SupportDAOFork,
+ utils.OpposeDAOFork,
utils.MinerThreadsFlag,
utils.MiningEnabledFlag,
utils.MiningGPUFlag,
@@ -225,12 +226,6 @@ participating.
eth.EnableBadBlockReporting = true
utils.SetupNetwork(ctx)
-
- // Deprecation warning.
- if ctx.GlobalIsSet(utils.GenesisFileFlag.Name) {
- common.PrintDepricationWarning("--genesis is deprecated. Switch to use 'geth init /path/to/file'")
- }
-
return nil
}
diff --git a/cmd/geth/usage.go b/cmd/geth/usage.go
index e7ef9e2c7b..eb897d2b5a 100644
--- a/cmd/geth/usage.go
+++ b/cmd/geth/usage.go
@@ -68,7 +68,6 @@ var AppHelpFlagGroups = []flagGroup{
utils.OlympicFlag,
utils.TestNetFlag,
utils.DevModeFlag,
- utils.GenesisFileFlag,
utils.IdentityFlag,
utils.FastSyncFlag,
utils.LightKDFFlag,
diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
index 38ba3a9ba0..fae1647b3e 100644
--- a/cmd/utils/flags.go
+++ b/cmd/utils/flags.go
@@ -126,10 +126,6 @@ var (
Name: "dev",
Usage: "Developer mode: pre-configured private network with several debugging flags",
}
- GenesisFileFlag = cli.StringFlag{
- Name: "genesis",
- Usage: "Insert/overwrite the genesis block (JSON format)",
- }
IdentityFlag = cli.StringFlag{
Name: "identity",
Usage: "Custom node name",
@@ -161,6 +157,15 @@ var (
Name: "lightkdf",
Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
}
+ // Fork settings
+ SupportDAOFork = cli.BoolFlag{
+ Name: "support-dao-fork",
+ Usage: "Updates the chain rules to support the DAO hard-fork",
+ }
+ OpposeDAOFork = cli.BoolFlag{
+ Name: "oppose-dao-fork",
+ Usage: "Updates the chain rules to oppose the DAO hard-fork",
+ }
// Miner settings
// TODO: refactor CPU vs GPU mining flags
MiningEnabledFlag = cli.BoolFlag{
@@ -534,20 +539,6 @@ func MakeWSRpcHost(ctx *cli.Context) string {
return ctx.GlobalString(WSListenAddrFlag.Name)
}
-// MakeGenesisBlock loads up a genesis block from an input file specified in the
-// command line, or returns the empty string if none set.
-func MakeGenesisBlock(ctx *cli.Context) string {
- genesis := ctx.GlobalString(GenesisFileFlag.Name)
- if genesis == "" {
- return ""
- }
- data, err := ioutil.ReadFile(genesis)
- if err != nil {
- Fatalf("Failed to load custom genesis file: %v", err)
- }
- return string(data)
-}
-
// MakeDatabaseHandles raises out the number of allowed file handles per process
// for Geth and returns half of the allowance to assign to the database.
func MakeDatabaseHandles() int {
@@ -689,7 +680,6 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
ethConf := ð.Config{
ChainConfig: MustMakeChainConfig(ctx),
- Genesis: MakeGenesisBlock(ctx),
FastSync: ctx.GlobalBool(FastSyncFlag.Name),
BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
@@ -722,17 +712,13 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
ethConf.NetworkId = 1
}
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.OlympicGenesisBlock()
- }
+ ethConf.Genesis = core.OlympicGenesisBlock()
case ctx.GlobalBool(TestNetFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
ethConf.NetworkId = 2
}
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.TestNetGenesisBlock()
- }
+ ethConf.Genesis = core.TestNetGenesisBlock()
state.StartingNonce = 1048576 // (2**20)
case ctx.GlobalBool(DevModeFlag.Name):
@@ -747,9 +733,7 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
stackConf.ListenAddr = ":0"
}
// Override the Ethereum protocol configs
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.OlympicGenesisBlock()
- }
+ ethConf.Genesis = core.OlympicGenesisBlock()
if !ctx.GlobalIsSet(GasPriceFlag.Name) {
ethConf.GasPrice = new(big.Int)
}
@@ -813,24 +797,43 @@ func MustMakeChainConfig(ctx *cli.Context) *core.ChainConfig {
// MustMakeChainConfigFromDb reads the chain configuration from the given database.
func MustMakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *core.ChainConfig {
- genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
+ // If the chain is already initialized, use any existing chain configs
+ config := new(core.ChainConfig)
- if genesis != nil {
- // Existing genesis block, use stored config if available.
+ if genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0); genesis != nil {
storedConfig, err := core.GetChainConfig(db, genesis.Hash())
- if err == nil {
- return storedConfig
- } else if err != core.ChainConfigNotFoundErr {
+ switch err {
+ case nil:
+ config = storedConfig
+ case core.ChainConfigNotFoundErr:
+ // No configs found, use empty, will populate below
+ default:
Fatalf("Could not make chain configuration: %v", err)
}
}
- var homesteadBlockNo *big.Int
- if ctx.GlobalBool(TestNetFlag.Name) {
- homesteadBlockNo = params.TestNetHomesteadBlock
- } else {
- homesteadBlockNo = params.MainNetHomesteadBlock
+ // Set any missing fields due to them being unset or system upgrade
+ if config.HomesteadBlock == nil {
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ config.HomesteadBlock = new(big.Int).Set(params.TestNetHomesteadBlock)
+ } else {
+ config.HomesteadBlock = new(big.Int).Set(params.MainNetHomesteadBlock)
+ }
}
- return &core.ChainConfig{HomesteadBlock: homesteadBlockNo}
+ if config.DAOForkBlock == nil {
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ config.DAOForkBlock = new(big.Int).Set(params.TestNetDAOForkBlock)
+ } else {
+ config.DAOForkBlock = new(big.Int).Set(params.MainNetDAOForkBlock)
+ }
+ }
+ // Force override any existing configs if explicitly requested
+ switch {
+ case ctx.GlobalBool(SupportDAOFork.Name):
+ config.DAOForkSupport = true
+ case ctx.GlobalBool(OpposeDAOFork.Name):
+ config.DAOForkSupport = false
+ }
+ return config
}
// MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
diff --git a/core/block_validator.go b/core/block_validator.go
index c3f959324a..3b597310ea 100644
--- a/core/block_validator.go
+++ b/core/block_validator.go
@@ -17,6 +17,7 @@
package core
import (
+ "bytes"
"fmt"
"math/big"
"time"
@@ -247,6 +248,33 @@ func ValidateHeader(config *ChainConfig, pow pow.PoW, header *types.Header, pare
return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()}
}
}
+ // If all checks passed, validate the extra-data field for hard forks
+ return ValidateHeaderExtraData(config, header)
+}
+
+// ValidateHeaderExtraData validates the extra-data field of a block header to
+// ensure it conforms to hard-fork rules.
+func ValidateHeaderExtraData(config *ChainConfig, header *types.Header) error {
+ // DAO hard-fork extension to the header validity: a) if the node is no-fork,
+ // do not accept blocks in the [fork, fork+10) range with the fork specific
+ // extra-data set; b) if the node is pro-fork, require blocks in the specific
+ // range to have the unique extra-data set.
+ if daoBlock := config.DAOForkBlock; daoBlock != nil {
+ // Check whether the block is among the fork extra-override range
+ limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
+ if daoBlock.Cmp(header.Number) <= 0 && header.Number.Cmp(limit) < 0 {
+ // Depending whether we support or oppose the fork, verrift the extra-data contents
+ if config.DAOForkSupport {
+ if bytes.Compare(header.Extra, params.DAOForkBlockExtra) != 0 {
+ return ValidationError("DAO pro-fork bad block extra-data: 0x%x", header.Extra)
+ }
+ } else {
+ if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 {
+ return ValidationError("DAO no-fork bad block extra-data: 0x%x", header.Extra)
+ }
+ }
+ }
+ }
return nil
}
diff --git a/core/block_validator_test.go b/core/block_validator_test.go
index c6daf9e7f3..5320c3f8da 100644
--- a/core/block_validator_test.go
+++ b/core/block_validator_test.go
@@ -27,6 +27,7 @@ import (
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
+ "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow/ezp"
)
@@ -92,3 +93,107 @@ func TestPutReceipt(t *testing.T) {
t.Error("expected to get 1 receipt, got none.")
}
}
+
+// Tests that DAO-fork enabled clients can properly filter out fork-commencing
+// blocks based on their extradata fields.
+func TestDAOForkRangeExtradata(t *testing.T) {
+ forkBlock := big.NewInt(32)
+
+ // Generate a common prefix for both pro-forkers and non-forkers
+ db, _ := ethdb.NewMemDatabase()
+ genesis := WriteGenesisBlockForTesting(db)
+ prefix, _ := GenerateChain(genesis, db, int(forkBlock.Int64()-1), func(i int, gen *BlockGen) {})
+
+ // Create the concurrent, conflicting two nodes
+ proDb, _ := ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(proDb)
+ proBc, _ := NewBlockChain(proDb, &ChainConfig{HomesteadBlock: big.NewInt(0), DAOForkBlock: forkBlock, DAOForkSupport: true}, new(FakePow), new(event.TypeMux))
+
+ conDb, _ := ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(conDb)
+ conBc, _ := NewBlockChain(conDb, &ChainConfig{HomesteadBlock: big.NewInt(0), DAOForkBlock: forkBlock, DAOForkSupport: false}, new(FakePow), new(event.TypeMux))
+
+ if _, err := proBc.InsertChain(prefix); err != nil {
+ t.Fatalf("pro-fork: failed to import chain prefix: %v", err)
+ }
+ if _, err := conBc.InsertChain(prefix); err != nil {
+ t.Fatalf("con-fork: failed to import chain prefix: %v", err)
+ }
+ // Try to expand both pro-fork and non-fork chains iteratively with other camp's blocks
+ for i := int64(0); i < params.DAOForkExtraRange.Int64(); i++ {
+ // Create a pro-fork block, and try to feed into the no-fork chain
+ db, _ = ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(db)
+ bc, _ := NewBlockChain(db, &ChainConfig{HomesteadBlock: big.NewInt(0)}, new(FakePow), new(event.TypeMux))
+
+ blocks := conBc.GetBlocksFromHash(conBc.CurrentBlock().Hash(), int(conBc.CurrentBlock().NumberU64()+1))
+ for j := 0; j < len(blocks)/2; j++ {
+ blocks[j], blocks[len(blocks)-1-j] = blocks[len(blocks)-1-j], blocks[j]
+ }
+ if _, err := bc.InsertChain(blocks); err != nil {
+ t.Fatalf("failed to import contra-fork chain for expansion: %v", err)
+ }
+ blocks, _ = GenerateChain(conBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) { gen.SetExtra(params.DAOForkBlockExtra) })
+ if _, err := conBc.InsertChain(blocks); err == nil {
+ t.Fatalf("contra-fork chain accepted pro-fork block: %v", blocks[0])
+ }
+ // Create a proper no-fork block for the contra-forker
+ blocks, _ = GenerateChain(conBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) {})
+ if _, err := conBc.InsertChain(blocks); err != nil {
+ t.Fatalf("contra-fork chain didn't accepted no-fork block: %v", err)
+ }
+ // Create a no-fork block, and try to feed into the pro-fork chain
+ db, _ = ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(db)
+ bc, _ = NewBlockChain(db, &ChainConfig{HomesteadBlock: big.NewInt(0)}, new(FakePow), new(event.TypeMux))
+
+ blocks = proBc.GetBlocksFromHash(proBc.CurrentBlock().Hash(), int(proBc.CurrentBlock().NumberU64()+1))
+ for j := 0; j < len(blocks)/2; j++ {
+ blocks[j], blocks[len(blocks)-1-j] = blocks[len(blocks)-1-j], blocks[j]
+ }
+ if _, err := bc.InsertChain(blocks); err != nil {
+ t.Fatalf("failed to import pro-fork chain for expansion: %v", err)
+ }
+ blocks, _ = GenerateChain(proBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) {})
+ if _, err := proBc.InsertChain(blocks); err == nil {
+ t.Fatalf("pro-fork chain accepted contra-fork block: %v", blocks[0])
+ }
+ // Create a proper pro-fork block for the pro-forker
+ blocks, _ = GenerateChain(proBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) { gen.SetExtra(params.DAOForkBlockExtra) })
+ if _, err := proBc.InsertChain(blocks); err != nil {
+ t.Fatalf("pro-fork chain didn't accepted pro-fork block: %v", err)
+ }
+ }
+ // Verify that contra-forkers accept pro-fork extra-datas after forking finishes
+ db, _ = ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(db)
+ bc, _ := NewBlockChain(db, &ChainConfig{HomesteadBlock: big.NewInt(0)}, new(FakePow), new(event.TypeMux))
+
+ blocks := conBc.GetBlocksFromHash(conBc.CurrentBlock().Hash(), int(conBc.CurrentBlock().NumberU64()+1))
+ for j := 0; j < len(blocks)/2; j++ {
+ blocks[j], blocks[len(blocks)-1-j] = blocks[len(blocks)-1-j], blocks[j]
+ }
+ if _, err := bc.InsertChain(blocks); err != nil {
+ t.Fatalf("failed to import contra-fork chain for expansion: %v", err)
+ }
+ blocks, _ = GenerateChain(conBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) { gen.SetExtra(params.DAOForkBlockExtra) })
+ if _, err := conBc.InsertChain(blocks); err != nil {
+ t.Fatalf("contra-fork chain didn't accept pro-fork block post-fork: %v", err)
+ }
+ // Verify that pro-forkers accept contra-fork extra-datas after forking finishes
+ db, _ = ethdb.NewMemDatabase()
+ WriteGenesisBlockForTesting(db)
+ bc, _ = NewBlockChain(db, &ChainConfig{HomesteadBlock: big.NewInt(0)}, new(FakePow), new(event.TypeMux))
+
+ blocks = proBc.GetBlocksFromHash(proBc.CurrentBlock().Hash(), int(proBc.CurrentBlock().NumberU64()+1))
+ for j := 0; j < len(blocks)/2; j++ {
+ blocks[j], blocks[len(blocks)-1-j] = blocks[len(blocks)-1-j], blocks[j]
+ }
+ if _, err := bc.InsertChain(blocks); err != nil {
+ t.Fatalf("failed to import pro-fork chain for expansion: %v", err)
+ }
+ blocks, _ = GenerateChain(proBc.CurrentBlock(), db, 1, func(i int, gen *BlockGen) {})
+ if _, err := proBc.InsertChain(blocks); err != nil {
+ t.Fatalf("pro-fork chain didn't accept contra-fork block post-fork: %v", err)
+ }
+}
diff --git a/core/config.go b/core/config.go
index 81ca76aa31..c0d065a57f 100644
--- a/core/config.go
+++ b/core/config.go
@@ -31,16 +31,17 @@ var ChainConfigNotFoundErr = errors.New("ChainConfig not found") // general conf
// that any network, identified by its genesis block, can have its own
// set of configuration options.
type ChainConfig struct {
- HomesteadBlock *big.Int // homestead switch block
+ HomesteadBlock *big.Int `json:"homesteadBlock"` // Homestead switch block (nil = no fork, 0 = already homestead)
+ DAOForkBlock *big.Int `json:"daoForkBlock"` // TheDAO hard-fork switch block (nil = no fork)
+ DAOForkSupport bool `json:"daoForkSupport"` // Whether the nodes supports or opposes the DAO hard-fork
VmConfig vm.Config `json:"-"`
}
// IsHomestead returns whether num is either equal to the homestead block or greater.
func (c *ChainConfig) IsHomestead(num *big.Int) bool {
- if num == nil {
+ if c.HomesteadBlock == nil || num == nil {
return false
}
-
return num.Cmp(c.HomesteadBlock) >= 0
}
diff --git a/eth/backend.go b/eth/backend.go
index 351cc27445..c8a9af6eee 100644
--- a/eth/backend.go
+++ b/eth/backend.go
@@ -205,6 +205,8 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
if config.ChainConfig == nil {
return nil, errors.New("missing chain config")
}
+ core.WriteChainConfig(chainDb, genesis.Hash(), config.ChainConfig)
+
eth.chainConfig = config.ChainConfig
eth.chainConfig.VmConfig = vm.Config{
EnableJit: config.EnableJit,
diff --git a/eth/handler.go b/eth/handler.go
index 47a36cc0bf..946d5930fa 100644
--- a/eth/handler.go
+++ b/eth/handler.go
@@ -45,6 +45,10 @@ const (
estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header
)
+var (
+ daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
+)
+
// errIncompatibleConfig is returned if the requested protocols and configs are
// not compatible (low protocol version restrictions and high requirements).
var errIncompatibleConfig = errors.New("incompatible configuration")
@@ -62,9 +66,10 @@ type ProtocolManager struct {
fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
synced uint32 // Flag whether we're considered synchronised (enables transaction processing)
- txpool txPool
- blockchain *core.BlockChain
- chaindb ethdb.Database
+ txpool txPool
+ blockchain *core.BlockChain
+ chaindb ethdb.Database
+ chainconfig *core.ChainConfig
downloader *downloader.Downloader
fetcher *fetcher.Fetcher
@@ -99,6 +104,7 @@ func NewProtocolManager(config *core.ChainConfig, fastSync bool, networkId int,
txpool: txpool,
blockchain: blockchain,
chaindb: chaindb,
+ chainconfig: config,
peers: newPeerSet(),
newPeerCh: make(chan *peer),
noMorePeers: make(chan struct{}),
@@ -278,6 +284,18 @@ func (pm *ProtocolManager) handle(p *peer) error {
// after this will be sent via broadcasts.
pm.syncTransactions(p)
+ // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
+ if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
+ // Request the peer's DAO fork header for extra-data validation
+ if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
+ return err
+ }
+ // Start a timer to disconnect if the peer doesn't reply in time
+ p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
+ glog.V(logger.Warn).Infof("%v: timed out DAO fork-check, dropping", p)
+ pm.removePeer(p.id)
+ })
+ }
// main loop. handle incoming messages.
for {
if err := pm.handleMsg(p); err != nil {
@@ -481,9 +499,43 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
if err := msg.Decode(&headers); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
+ // If no headers were received, but we're expending a DAO fork check, maybe it's that
+ if len(headers) == 0 && p.forkDrop != nil {
+ // Possibly an empty reply to the fork header checks, sanity check TDs
+ verifyDAO := true
+
+ // If we already have a DAO header, we can check the peer's TD against it. If
+ // the peer's ahead of this, it too must have a reply to the DAO check
+ if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
+ if p.Td().Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
+ verifyDAO = false
+ }
+ }
+ // If we're seemingly on the same chain, disable the drop timer
+ if verifyDAO {
+ glog.V(logger.Info).Infof("%v: seems to be on the same side of the DAO fork", p)
+ p.forkDrop.Stop()
+ p.forkDrop = nil
+ return nil
+ }
+ }
// Filter out any explicitly requested headers, deliver the rest to the downloader
filter := len(headers) == 1
if filter {
+ // If it's a potential DAO fork check, validate against the rules
+ if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
+ // Disable the fork drop timer
+ p.forkDrop.Stop()
+ p.forkDrop = nil
+
+ // Validate the header and either drop the peer or continue
+ if err := core.ValidateHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
+ glog.V(logger.Info).Infof("%v: verified to be on the other side of the DAO fork, dropping", p)
+ return err
+ }
+ glog.V(logger.Info).Infof("%v: verified to be on the same side of the DAO fork", p)
+ }
+ // Irrelevant of the fork checks, send the header to the fetcher just in case
headers = pm.fetcher.FilterHeaders(headers, time.Now())
}
if len(headers) > 0 || !filter {
diff --git a/eth/handler_test.go b/eth/handler_test.go
index 8418c28b23..d5b1bf3508 100644
--- a/eth/handler_test.go
+++ b/eth/handler_test.go
@@ -20,6 +20,7 @@ import (
"math/big"
"math/rand"
"testing"
+ "time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
@@ -28,6 +29,7 @@ import (
"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"
"github.com/ethereum/go-ethereum/params"
)
@@ -580,3 +582,74 @@ func testGetReceipt(t *testing.T, protocol int) {
t.Errorf("receipts mismatch: %v", err)
}
}
+
+// Tests that post eth protocol handshake, DAO fork-enabled clients also execute
+// a DAO "challenge" verifying each others' DAO fork headers to ensure they're on
+// compatible chains.
+func TestDAOChallengeNoVsNo(t *testing.T) { testDAOChallenge(t, false, false, false) }
+func TestDAOChallengeNoVsPro(t *testing.T) { testDAOChallenge(t, false, true, false) }
+func TestDAOChallengeProVsNo(t *testing.T) { testDAOChallenge(t, true, false, false) }
+func TestDAOChallengeProVsPro(t *testing.T) { testDAOChallenge(t, true, true, false) }
+func TestDAOChallengeNoVsTimeout(t *testing.T) { testDAOChallenge(t, false, false, true) }
+func TestDAOChallengeProVsTimeout(t *testing.T) { testDAOChallenge(t, true, true, true) }
+
+func testDAOChallenge(t *testing.T, localForked, remoteForked bool, timeout bool) {
+ // Reduce the DAO handshake challenge timeout
+ if timeout {
+ defer func(old time.Duration) { daoChallengeTimeout = old }(daoChallengeTimeout)
+ daoChallengeTimeout = 500 * time.Millisecond
+ }
+ // Create a DAO aware protocol manager
+ var (
+ evmux = new(event.TypeMux)
+ pow = new(core.FakePow)
+ db, _ = ethdb.NewMemDatabase()
+ genesis = core.WriteGenesisBlockForTesting(db)
+ config = &core.ChainConfig{DAOForkBlock: big.NewInt(1), DAOForkSupport: localForked}
+ blockchain, _ = core.NewBlockChain(db, config, pow, evmux)
+ )
+ pm, err := NewProtocolManager(config, false, NetworkId, evmux, new(testTxPool), pow, blockchain, db)
+ if err != nil {
+ t.Fatalf("failed to start test protocol manager: %v", err)
+ }
+ pm.Start()
+ defer pm.Stop()
+
+ // Connect a new peer and check that we receive the DAO challenge
+ peer, _ := newTestPeer("peer", eth63, pm, true)
+ defer peer.close()
+
+ challenge := &getBlockHeadersData{
+ Origin: hashOrNumber{Number: config.DAOForkBlock.Uint64()},
+ Amount: 1,
+ Skip: 0,
+ Reverse: false,
+ }
+ if err := p2p.ExpectMsg(peer.app, GetBlockHeadersMsg, challenge); err != nil {
+ t.Fatalf("challenge mismatch: %v", err)
+ }
+ // Create a block to reply to the challenge if no timeout is simualted
+ if !timeout {
+ blocks, _ := core.GenerateChain(genesis, db, 1, func(i int, block *core.BlockGen) {
+ if remoteForked {
+ block.SetExtra(params.DAOForkBlockExtra)
+ }
+ })
+ if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{blocks[0].Header()}); err != nil {
+ t.Fatalf("failed to answer challenge: %v", err)
+ }
+ } else {
+ // Otherwise wait until the test timeout passes
+ time.Sleep(daoChallengeTimeout + 500*time.Millisecond)
+ }
+ // Verify that depending on fork side, the remote peer is maintained or dropped
+ if localForked == remoteForked && !timeout {
+ if peers := pm.peers.Len(); peers != 1 {
+ t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
+ }
+ } else {
+ if peers := pm.peers.Len(); peers != 0 {
+ t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
+ }
+ }
+}
diff --git a/eth/peer.go b/eth/peer.go
index 8eb41b0f99..b97825c69e 100644
--- a/eth/peer.go
+++ b/eth/peer.go
@@ -59,10 +59,12 @@ type peer struct {
*p2p.Peer
rw p2p.MsgReadWriter
- version int // Protocol version negotiated
- head common.Hash
- td *big.Int
- lock sync.RWMutex
+ version int // Protocol version negotiated
+ forkDrop *time.Timer // Timed connection dropper if forks aren't validated in time
+
+ head common.Hash
+ td *big.Int
+ lock sync.RWMutex
knownTxs *set.Set // Set of transaction hashes known to be known by this peer
knownBlocks *set.Set // Set of block hashes known to be known by this peer
diff --git a/miner/worker.go b/miner/worker.go
index 09cf6b6aa7..ba0085d521 100644
--- a/miner/worker.go
+++ b/miner/worker.go
@@ -17,6 +17,7 @@
package miner
import (
+ "bytes"
"fmt"
"math/big"
"sync"
@@ -33,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
+ "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow"
"gopkg.in/fatih/set.v0"
)
@@ -468,7 +470,19 @@ func (self *worker) commitNewWork() {
Extra: self.extra,
Time: big.NewInt(tstamp),
}
-
+ // If we are care about TheDAO hard-fork check whether to override the extra-data or not
+ if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
+ // Check whether the block is among the fork extra-override range
+ limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
+ if daoBlock.Cmp(header.Number) <= 0 && header.Number.Cmp(limit) < 0 {
+ // Depending whether we support or oppose the fork, override differently
+ if self.config.DAOForkSupport {
+ header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
+ } else if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 {
+ header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
+ }
+ }
+ }
previous := self.current
// Could potentially happen if starting to mine in an odd state.
err := self.makeCurrent(parent, header)
diff --git a/params/util.go b/params/util.go
index b37bc79b21..a0c9a3199a 100644
--- a/params/util.go
+++ b/params/util.go
@@ -16,9 +16,18 @@
package params
-import "math/big"
+import (
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/common"
+)
var (
- TestNetHomesteadBlock = big.NewInt(494000) // testnet homestead block
- MainNetHomesteadBlock = big.NewInt(1150000) // mainnet homestead block
+ TestNetHomesteadBlock = big.NewInt(494000) // Testnet homestead block
+ MainNetHomesteadBlock = big.NewInt(1150000) // Mainnet homestead block
+
+ TestNetDAOForkBlock = big.NewInt(8888888) // Testnet dao hard-fork block
+ MainNetDAOForkBlock = big.NewInt(9999999) // Mainnet dao hard-fork block
+ DAOForkBlockExtra = common.FromHex("0x64616f2d686172642d666f726b") // Block extradata to signel the fork with ("dao-hard-fork")
+ DAOForkExtraRange = big.NewInt(10) // Number of blocks to override the extradata (prevent no-fork attacks)
)