Commit feeccdf4 authored by Péter Szilágyi's avatar Péter Szilágyi Committed by Felix Lange

consensus/clique: Proof of Authority (#3753)

This PR is a prototype implementation of plugable consensus engines and the
Clique PoA protocol ethereum/EIPs#225
parent bfe5eb7f
// Copyright 2017 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 <http://www.gnu.org/licenses/>.
package clique
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rpc"
)
// API is a user facing RPC API to allow controlling the signer and voting
// mechanisms of the proof-of-authority scheme.
type API struct {
chain consensus.ChainReader
clique *Clique
}
// GetSnapshot retrieves the state snapshot at a given block.
func (api *API) GetSnapshot(number *rpc.BlockNumber) (interface{}, error) {
// Retrieve the requested block number (or current if none requested)
var header *types.Header
if number == nil || *number == rpc.LatestBlockNumber {
header = api.chain.CurrentHeader()
} else {
header = api.chain.GetHeaderByNumber(uint64(number.Int64()))
}
// Ensure we have an actually valid block and return its snapshot
if header == nil {
return nil, errUnknownBlock
}
return api.clique.snapshot(api.chain, header.Number.Uint64(), header.Hash(), nil)
}
// GetSigners retrieves the list of authorized signers at the specified block.
func (api *API) GetSigners(number *rpc.BlockNumber) ([]common.Address, error) {
// Retrieve the requested block number (or current if none requested)
var header *types.Header
if number == nil || *number == rpc.LatestBlockNumber {
header = api.chain.CurrentHeader()
} else {
header = api.chain.GetHeaderByNumber(uint64(number.Int64()))
}
// Ensure we have an actually valid block and return the signers from its snapshot
if header == nil {
return nil, errUnknownBlock
}
snap, err := api.clique.snapshot(api.chain, header.Number.Uint64(), header.Hash(), nil)
if err != nil {
return nil, err
}
return snap.signers(), nil
}
// Proposals returns the current proposals the node tries to uphold and vote on.
func (api *API) Proposals() map[common.Address]bool {
api.clique.lock.RLock()
defer api.clique.lock.RUnlock()
proposals := make(map[common.Address]bool)
for address, auth := range api.clique.proposals {
proposals[address] = auth
}
return proposals
}
// Propose injects a new authorization proposal that the signer will attempt to
// push through.
func (api *API) Propose(address common.Address, auth bool) {
api.clique.lock.Lock()
defer api.clique.lock.Unlock()
api.clique.proposals[address] = auth
}
// Discard drops a currently running proposal, stopping the signer from casting
// further votes (either for or against).
func (api *API) Discard(address common.Address) {
api.clique.lock.Lock()
defer api.clique.lock.Unlock()
delete(api.clique.proposals, address)
}
This diff is collapsed.
// Copyright 2017 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 <http://www.gnu.org/licenses/>.
package clique
import (
"bytes"
"encoding/json"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
)
// vote represents a single vote that an authorized signer made to modify the
// list of authorizations.
type vote struct {
Signer common.Address `json:"signer"` // Authorized signer that cast this vote
Block uint64 `json:"block"` // Block number the vote was cast in (expire old votes)
Address common.Address `json:"address"` // Account being voted on to change its authorization
Authorize bool `json:"authorize"` // Whether to authorize or deauthorize the voted account
}
// tally is a simple vote tally to keep the current score of votes. Votes that
// go against the proposal aren't counted since it's equivalent to not voting.
type tally struct {
Authorize bool `json:"authorize"` // Whether the vote it about authorizing or kicking someone
Votes int `json:"votes"` // Number of votes until now wanting to pass the proposal
}
// snapshot is the state of the authorization voting at a given point in time.
type snapshot struct {
config *params.CliqueConfig // Consensus engine parameters to fine tune behavior
Number uint64 `json:"number"` // Block number where the snapshot was created
Hash common.Hash `json:"hash"` // Block hash where the snapshot was created
Signers map[common.Address]struct{} `json:"signers"` // Set of authorized signers at this moment
Recents map[uint64]common.Address `json:"recents"` // Set of recent signers for spam protections
Votes []*vote `json:"votes"` // List of votes cast in chronological order
Tally map[common.Address]tally `json:"tally"` // Current vote tally to avoid recalculating
}
// newSnapshot create a new snapshot with the specified startup parameters. This
// method does not initialize the set of recent signers, so only ever use if for
// the genesis block.
func newSnapshot(config *params.CliqueConfig, number uint64, hash common.Hash, signers []common.Address) *snapshot {
snap := &snapshot{
config: config,
Number: number,
Hash: hash,
Signers: make(map[common.Address]struct{}),
Recents: make(map[uint64]common.Address),
Tally: make(map[common.Address]tally),
}
for _, signer := range signers {
snap.Signers[signer] = struct{}{}
}
return snap
}
// loadSnapshot loads an existing snapshot from the database.
func loadSnapshot(config *params.CliqueConfig, db ethdb.Database, hash common.Hash) (*snapshot, error) {
blob, err := db.Get(append([]byte("clique-"), hash[:]...))
if err != nil {
return nil, err
}
snap := new(snapshot)
if err := json.Unmarshal(blob, snap); err != nil {
return nil, err
}
snap.config = config
return snap, nil
}
// store inserts the snapshot into the database.
func (s *snapshot) store(db ethdb.Database) error {
blob, err := json.Marshal(s)
if err != nil {
return err
}
return db.Put(append([]byte("clique-"), s.Hash[:]...), blob)
}
// copy creates a deep copy of the snapshot, though not the individual votes.
func (s *snapshot) copy() *snapshot {
cpy := &snapshot{
config: s.config,
Number: s.Number,
Hash: s.Hash,
Signers: make(map[common.Address]struct{}),
Recents: make(map[uint64]common.Address),
Votes: make([]*vote, len(s.Votes)),
Tally: make(map[common.Address]tally),
}
for signer := range s.Signers {
cpy.Signers[signer] = struct{}{}
}
for block, signer := range s.Recents {
cpy.Recents[block] = signer
}
for address, tally := range s.Tally {
cpy.Tally[address] = tally
}
copy(cpy.Votes, s.Votes)
return cpy
}
// cast adds a new vote into the tally.
func (s *snapshot) cast(address common.Address, authorize bool) bool {
// Ensure the vote is meaningful
_, signer := s.Signers[address]
if (signer && authorize) || (!signer && !authorize) {
return false
}
// Cast the vote into an existing or new tally
if old, ok := s.Tally[address]; ok {
old.Votes++
s.Tally[address] = old
} else {
s.Tally[address] = tally{Authorize: authorize, Votes: 1}
}
return true
}
// uncast removes a previously cast vote from the tally.
func (s *snapshot) uncast(address common.Address, authorize bool) bool {
// If there's no tally, it's a dangling vote, just drop
tally, ok := s.Tally[address]
if !ok {
return false
}
// Ensure we only revert counted votes
if tally.Authorize != authorize {
return false
}
// Otherwise revert the vote
if tally.Votes > 1 {
tally.Votes--
s.Tally[address] = tally
} else {
delete(s.Tally, address)
}
return true
}
// apply creates a new authorization snapshot by applying the given headers to
// the original one.
func (s *snapshot) apply(headers []*types.Header) (*snapshot, error) {
// Allow passing in no headers for cleaner code
if len(headers) == 0 {
return s, nil
}
// Sanity check that the headers can be applied
for i := 0; i < len(headers)-1; i++ {
if headers[i+1].Number.Uint64() != headers[i].Number.Uint64()+1 {
return nil, errInvalidVotingChain
}
}
if headers[0].Number.Uint64() != s.Number+1 {
return nil, errInvalidVotingChain
}
// Iterate through the headers and create a new snapshot
snap := s.copy()
for _, header := range headers {
// Remove any votes on checkpoint blocks
number := header.Number.Uint64()
if number%s.config.Epoch == 0 {
snap.Votes = nil
snap.Tally = make(map[common.Address]tally)
}
// Delete the oldest signer from the recent list to allow it signing again
if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
delete(snap.Recents, number-limit)
}
// Resolve the authorization key and check against signers
signer, err := ecrecover(header)
if err != nil {
return nil, err
}
if _, ok := snap.Signers[signer]; !ok {
return nil, errUnauthorized
}
for _, recent := range snap.Recents {
if recent == signer {
return nil, errUnauthorized
}
}
snap.Recents[number] = signer
// Header authorized, discard any previous votes from the signer
for i, vote := range snap.Votes {
if vote.Signer == signer && vote.Address == header.Coinbase {
// Uncast the vote from the cached tally
snap.uncast(vote.Address, vote.Authorize)
// Uncast the vote from the chronological list
snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
break // only one vote allowed
}
}
// Tally up the new vote from the signer
var authorize bool
switch {
case bytes.Compare(header.Nonce[:], nonceAuthVote) == 0:
authorize = true
case bytes.Compare(header.Nonce[:], nonceDropVote) == 0:
authorize = false
default:
return nil, errInvalidVote
}
if snap.cast(header.Coinbase, authorize) {
snap.Votes = append(snap.Votes, &vote{
Signer: signer,
Block: number,
Address: header.Coinbase,
Authorize: authorize,
})
}
// If the vote passed, update the list of signers
if tally := snap.Tally[header.Coinbase]; tally.Votes > len(snap.Signers)/2 {
if tally.Authorize {
snap.Signers[header.Coinbase] = struct{}{}
} else {
delete(snap.Signers, header.Coinbase)
// Signer list shrunk, delete any leftover recent caches
if limit := uint64(len(snap.Signers)/2 + 1); number >= limit {
delete(snap.Recents, number-limit)
}
// Discard any previous votes the deauthorized signer cast
for i := 0; i < len(snap.Votes); i++ {
if snap.Votes[i].Signer == header.Coinbase {
// Uncast the vote from the cached tally
snap.uncast(snap.Votes[i].Address, snap.Votes[i].Authorize)
// Uncast the vote from the chronological list
snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
i--
}
}
}
// Discard any previous votes around the just changed account
for i := 0; i < len(snap.Votes); i++ {
if snap.Votes[i].Address == header.Coinbase {
snap.Votes = append(snap.Votes[:i], snap.Votes[i+1:]...)
i--
}
}
delete(snap.Tally, header.Coinbase)
}
}
snap.Number += uint64(len(headers))
snap.Hash = headers[len(headers)-1].Hash()
return snap, nil
}
// signers retrieves the list of authorized signers in ascending order.
func (s *snapshot) signers() []common.Address {
signers := make([]common.Address, 0, len(s.Signers))
for signer := range s.Signers {
signers = append(signers, signer)
}
for i := 0; i < len(signers); i++ {
for j := i + 1; j < len(signers); j++ {
if bytes.Compare(signers[i][:], signers[j][:]) > 0 {
signers[i], signers[j] = signers[j], signers[i]
}
}
}
return signers
}
// inturn returns if a signer at a given block height is in-turn or not.
func (s *snapshot) inturn(number uint64, signer common.Address) bool {
signers, offset := s.signers(), 0
for offset < len(signers) && signers[offset] != signer {
offset++
}
return (number % uint64(len(signers))) == uint64(offset)
}
This diff is collapsed.
......@@ -23,14 +23,6 @@ var (
// that is unknown.
ErrUnknownAncestor = errors.New("unknown ancestor")
// ErrLargeBlockTime is returned if the value of the timestamp is beyond
// any reasonable value.
ErrLargeBlockTime = errors.New("timestamp too big")
// ErrZeroBlockTime is returned if the block's timestamp is the same as the one
// its parent has.
ErrZeroBlockTime = errors.New("timestamp equals parent's")
// ErrFutureBlock is returned when a block's timestamp is in the future according
// to the current node.
ErrFutureBlock = errors.New("block in the future")
......
......@@ -41,16 +41,22 @@ var (
maxUncles = 2 // Maximum number of uncles allowed in a single block
)
// Various error messages to mark blocks invalid. These should be private to
// prevent engine specific errors from being referenced in the remainder of the
// codebase, inherently breaking if the engine is swapped out. Please put common
// error types into the consensus package.
var (
ErrInvalidChain = errors.New("invalid header chain")
ErrTooManyUncles = errors.New("too many uncles")
ErrDuplicateUncle = errors.New("duplicate uncle")
ErrUncleIsAncestor = errors.New("uncle is ancestor")
ErrDanglingUncle = errors.New("uncle's parent is not ancestor")
ErrNonceOutOfRange = errors.New("nonce out of range")
ErrInvalidDifficulty = errors.New("non-positive difficulty")
ErrInvalidMixDigest = errors.New("invalid mix digest")
ErrInvalidPoW = errors.New("invalid proof-of-work")
errInvalidChain = errors.New("invalid header chain")
errLargeBlockTime = errors.New("timestamp too big")
errZeroBlockTime = errors.New("timestamp equals parent's")
errTooManyUncles = errors.New("too many uncles")
errDuplicateUncle = errors.New("duplicate uncle")
errUncleIsAncestor = errors.New("uncle is ancestor")
errDanglingUncle = errors.New("uncle's parent is not ancestor")
errNonceOutOfRange = errors.New("nonce out of range")
errInvalidDifficulty = errors.New("non-positive difficulty")
errInvalidMixDigest = errors.New("invalid mix digest")
errInvalidPoW = errors.New("invalid proof-of-work")
)
// VerifyHeader checks whether a header conforms to the consensus rules of the
......@@ -104,7 +110,7 @@ func (ethash *Ethash) VerifyHeaders(chain consensus.ChainReader, headers []*type
for index := range inputs {
// If we've found a bad block already before this, stop validating
if bad := atomic.LoadUint64(&badblock); bad != 0 && bad <= headers[index].Number.Uint64() {
outputs <- result{index: index, err: ErrInvalidChain}
outputs <- result{index: index, err: errInvalidChain}
continue
}
// We need to look up the first parent
......@@ -194,7 +200,7 @@ func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Blo
}
// Verify that there are at most 2 uncles included in this block
if len(block.Uncles()) > maxUncles {
return ErrTooManyUncles
return errTooManyUncles
}
// Gather the set of past uncles and ancestors
uncles, ancestors := set.New(), make(map[common.Hash]*types.Header)
......@@ -219,16 +225,16 @@ func (ethash *Ethash) VerifyUncles(chain consensus.ChainReader, block *types.Blo
// Make sure every uncle is rewarded only once
hash := uncle.Hash()
if uncles.Has(hash) {
return ErrDuplicateUncle
return errDuplicateUncle
}
uncles.Add(hash)
// Make sure the uncle has a valid ancestry
if ancestors[hash] != nil {
return ErrUncleIsAncestor
return errUncleIsAncestor
}
if ancestors[uncle.ParentHash] == nil || uncle.ParentHash == block.ParentHash() {
return ErrDanglingUncle
return errDanglingUncle
}
if err := ethash.verifyHeader(chain, uncle, ancestors[uncle.ParentHash], true, true); err != nil {
return err
......@@ -249,7 +255,7 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *
// Verify the header's timestamp
if uncle {
if header.Time.Cmp(math.MaxBig256) > 0 {
return consensus.ErrLargeBlockTime
return errLargeBlockTime
}
} else {
if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
......@@ -257,7 +263,7 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *
}
}
if header.Time.Cmp(parent.Time) <= 0 {
return consensus.ErrZeroBlockTime
return errZeroBlockTime
}
// Verify the block's difficulty based in it's timestamp and parent's difficulty
expected := CalcDifficulty(chain.Config(), header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
......@@ -403,7 +409,7 @@ func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Head
if ethash.fakeMode {
time.Sleep(ethash.fakeDelay)
if ethash.fakeFail == header.Number.Uint64() {
return ErrInvalidPoW
return errInvalidPoW
}
return nil
}
......@@ -415,11 +421,11 @@ func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Head
number := header.Number.Uint64()
if number/epochLength >= uint64(len(cacheSizes)) {
// Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check)
return ErrNonceOutOfRange
return errNonceOutOfRange
}
// Ensure that we have a valid difficulty for the block
if header.Difficulty.Sign() <= 0 {
return ErrInvalidDifficulty
return errInvalidDifficulty
}
// Recompute the digest and PoW value and verify against the header
cache := ethash.cache(number)
......@@ -430,11 +436,11 @@ func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Head
}
digest, result := hashimotoLight(size, cache, header.HashNoNonce().Bytes(), header.Nonce.Uint64())
if !bytes.Equal(header.MixDigest[:], digest) {
return ErrInvalidMixDigest
return errInvalidMixDigest
}
target := new(big.Int).Div(maxUint256, header.Difficulty)
if new(big.Int).SetBytes(result).Cmp(target) > 0 {
return ErrInvalidPoW
return errInvalidPoW
}
return nil
}
......
......@@ -532,13 +532,10 @@ func testInsertNonceError(t *testing.T, full bool) {
blockchain.hc.engine = blockchain.engine
failRes, err = blockchain.InsertHeaderChain(headers, 1)
}
// Check that the returned error indicates the nonce failure.
// Check that the returned error indicates the failure.
if failRes != failAt {
t.Errorf("test %d: failure index mismatch: have %d, want %d", i, failRes, failAt)
}
if err != ethash.ErrInvalidPoW {
t.Fatalf("test %d: error mismatch: have %v, want %v", i, err, ethash.ErrInvalidPoW)
}
// Check that all no blocks after the failing block have been inserted.
for j := 0; j < i-failAt; j++ {
if full {
......
......@@ -27,6 +27,7 @@ import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/consensus/clique"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
......@@ -230,6 +231,11 @@ func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Data
// 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 {
// If proof-of-authority is requested, set it up
if chainConfig.Clique != nil {
return clique.New(chainConfig.Clique, db)
}
// Otherwise assume proof-of-work
switch {
case config.PowFake:
log.Warn("Ethash used in fake mode")
......@@ -333,6 +339,14 @@ func (s *Ethereum) StartMining(local bool) error {
log.Error("Cannot start mining without etherbase", "err", err)
return fmt.Errorf("etherbase missing: %v", err)
}
if clique, ok := s.engine.(*clique.Clique); ok {
wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
if wallet == nil || err != nil {
log.Error("Etherbase account unavailable locally", "err", err)
return fmt.Errorf("singer missing: %v", err)
}
clique.Authorize(eb, wallet.SignHash)
}
if local {
// If local (CPU) mining is started, we can disable the transaction rejection
// mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
......
......@@ -20,6 +20,7 @@ package web3ext
var Modules = map[string]string{
"admin": Admin_JS,
"chequebook": Chequebook_JS,
"clique": Clique_JS,
"debug": Debug_JS,
"eth": Eth_JS,
"miner": Miner_JS,
......@@ -29,8 +30,10 @@ var Modules = map[string]string{
"shh": Shh_JS,
"swarmfs": SWARMFS_JS,
"txpool": TxPool_JS,
}
const Chequebook_JS = `
web3._extend({
property: 'chequebook',
......@@ -63,6 +66,44 @@ web3._extend({
});
`
const Clique_JS = `
web3._extend({
property: 'clique',
methods:
[
new web3._extend.Method({
name: 'getSnapshot',
call: 'clique_getSnapshot',
params: 1,
inputFormatter: [null]
}),
new web3._extend.Method({
name: 'getSigners',
call: 'clique_getSigners',
params: 1,
inputFormatter: [null]
}),
new web3._extend.Method({
name: 'propose',
call: 'clique_propose',
params: 2
}),
new web3._extend.Method({
name: 'discard',
call: 'clique_discard',
params: 1
})
],
properties:
[
new web3._extend.Property({
name: 'proposals',
getter: 'clique_proposals'
}),
]
});
`
const Admin_JS = `
web3._extend({
property: 'admin',
......
......@@ -55,10 +55,6 @@ type NodeConfig struct {
// decide if remote peers should be accepted or not.
EthereumNetworkID int
// EthereumChainConfig is the default parameters of the blockchain to use. If no
// configuration is specified, it defaults to the main network.
EthereumChainConfig *ChainConfig
// EthereumGenesis is the genesis JSON to use to seed the blockchain with. An
// empty genesis state is equivalent to using the mainnet's state.
EthereumGenesis string
......@@ -84,7 +80,6 @@ var defaultNodeConfig = &NodeConfig{
MaxPeers: 25,
EthereumEnabled: true,
EthereumNetworkID: 1,
EthereumChainConfig: MainnetChainConfig(),
EthereumDatabaseCache: 16,
}
......@@ -94,18 +89,6 @@ func NewNodeConfig() *NodeConfig {
return &config
}
// SetMainnet sets up the node for use on the Ethereum mainnet.
func (cfg *NodeConfig) SetMainnet() {
cfg.EthereumGenesis = ""
cfg.EthereumChainConfig = MainnetChainConfig()
}
// SetTestnet sets up the node for use on the Ethereum testnet.
func (cfg *NodeConfig) SetTestnet() {
cfg.EthereumGenesis = TestnetGenesis()
cfg.EthereumChainConfig = TestnetChainConfig()
}
// Node represents a Geth Ethereum node instance.
type Node struct {
node *node.Node
......@@ -144,27 +127,19 @@ func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
var genesis *core.Genesis
if config.EthereumGenesis != "" {
// Parse the user supplied genesis spec if not mainnet
genesis = new(core.Genesis)
if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
return nil, fmt.Errorf("invalid EthereumGenesis: %v", err)
}
return nil, fmt.Errorf("invalid genesis spec: %v", err)
}
if config.EthereumChainConfig != nil {
if genesis == nil {
genesis = core.DefaultGenesisBlock()
// If we have the testnet, hard code the chain configs too
if config.EthereumGenesis == TestnetGenesis() {
genesis.Config = params.TestnetChainConfig
if config.EthereumNetworkID == 1 {
config.EthereumNetworkID = 3
}
genesis.Config = &params.ChainConfig{
ChainId: big.NewInt(config.EthereumChainConfig.ChainID),
HomesteadBlock: big.NewInt(config.EthereumChainConfig.HomesteadBlock),
DAOForkBlock: big.NewInt(config.EthereumChainConfig.DAOForkBlock),
DAOForkSupport: config.EthereumChainConfig.DAOForkSupport,
EIP150Block: big.NewInt(config.EthereumChainConfig.EIP150Block),
EIP150Hash: config.EthereumChainConfig.EIP150Hash.hash,
EIP155Block: big.NewInt(config.EthereumChainConfig.EIP155Block),
EIP158Block: big.NewInt(config.EthereumChainConfig.EIP158Block),
}
}
// Register the Ethereum protocol if requested
if config.EthereumEnabled {
ethConf := &eth.Config{
......@@ -173,7 +148,7 @@ func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
DatabaseCache: config.EthereumDatabaseCache,
NetworkId: config.EthereumNetworkID,
GasPrice: new(big.Int).SetUint64(20 * params.Shannon),
GpoBlocks: 5,
GpoBlocks: 10,
GpoPercentile: 50,
EthashCacheDir: "ethash",
EthashCachesInMem: 2,
......
......@@ -26,40 +26,12 @@ import (
"github.com/ethereum/go-ethereum/params"
)
// MainnetChainConfig returns the chain configurations for the main Ethereum network.
func MainnetChainConfig() *ChainConfig {
return &ChainConfig{
ChainID: params.MainNetChainID.Int64(),
HomesteadBlock: params.MainNetHomesteadBlock.Int64(),
DAOForkBlock: params.MainNetDAOForkBlock.Int64(),
DAOForkSupport: true,
EIP150Block: params.MainNetHomesteadGasRepriceBlock.Int64(),
EIP150Hash: Hash{params.MainNetHomesteadGasRepriceHash},
EIP155Block: params.MainNetSpuriousDragon.Int64(),
EIP158Block: params.MainNetSpuriousDragon.Int64(),
}
}
// MainnetGenesis returns the JSON spec to use for the main Ethereum network. It
// is actually empty since that defaults to the hard coded binary genesis block.
func MainnetGenesis() string {
return ""
}
// TestnetChainConfig returns the chain configurations for the Ethereum test network.
func TestnetChainConfig() *ChainConfig {
return &ChainConfig{
ChainID: params.TestNetChainID.Int64(),
HomesteadBlock: params.TestNetHomesteadBlock.Int64(),
DAOForkBlock: 0,
DAOForkSupport: false,
EIP150Block: params.TestNetHomesteadGasRepriceBlock.Int64(),
EIP150Hash: Hash{params.TestNetHomesteadGasRepriceHash},
EIP155Block: params.TestNetSpuriousDragon.Int64(),
EIP158Block: params.TestNetSpuriousDragon.Int64(),
}
}
// TestnetGenesis returns the JSON spec to use for the Ethereum test network.
func TestnetGenesis() string {
enc, err := json.Marshal(core.DefaultTestnetGenesisBlock())
......@@ -69,24 +41,6 @@ func TestnetGenesis() string {
return string(enc)
}
// ChainConfig is the core config which determines the blockchain settings.
type ChainConfig struct {
ChainID int64 // Chain ID for replay protection
HomesteadBlock int64 // Homestead switch block
DAOForkBlock int64 // TheDAO hard-fork switch block
DAOForkSupport bool // Whether the nodes supports or opposes the DAO hard-fork
EIP150Block int64 // Homestead gas reprice switch block
EIP150Hash Hash // Homestead gas reprice switch block hash
EIP155Block int64 // Replay protection switch block
EIP158Block int64 // Empty account pruning switch block
}
// NewChainConfig creates a new chain configuration that transitions immediately
// to homestead and has no notion of the DAO fork (ideal for a private network).
func NewChainConfig() *ChainConfig {
return new(ChainConfig)
}
// FoundationBootnodes returns the enode URLs of the P2P bootstrap nodes operated
// by the foundation running the V5 discovery protocol.
func FoundationBootnodes() *Enodes {
......
......@@ -34,6 +34,7 @@ var (
EIP150Hash: MainNetHomesteadGasRepriceHash,
EIP155Block: MainNetSpuriousDragon,
EIP158Block: MainNetSpuriousDragon,
Ethash: new(EthashConfig),
}
// TestnetChainConfig contains the chain parameters to run a node on the ropsten test network.
......@@ -46,6 +47,7 @@ var (
EIP150Hash: common.HexToHash("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"),
EIP155Block: big.NewInt(10),
EIP158Block: big.NewInt(10),
Ethash: new(EthashConfig),
}
// AllProtocolChanges contains every protocol change (EIPs)
......@@ -57,8 +59,8 @@ var (
// means that all fields must be set at all times. This forces
// anyone adding flags to the config to also have to set these
// fields.
AllProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0)}
TestChainConfig = &ChainConfig{big.NewInt(1), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0)}
AllProtocolChanges = &ChainConfig{big.NewInt(1337), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), new(EthashConfig), nil}
TestChainConfig = &ChainConfig{big.NewInt(1), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), new(EthashConfig), nil}
)
// ChainConfig is the core config which determines the blockchain settings.
......@@ -69,21 +71,53 @@ var (
type ChainConfig struct {
ChainId *big.Int `json:"chainId"` // Chain id identifies the current chain and is used for replay protection
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
HomesteadBlock *big.Int `json:"homesteadBlock,omitempty"` // Homestead switch block (nil = no fork, 0 = already homestead)
DAOForkBlock *big.Int `json:"daoForkBlock,omitempty"` // TheDAO hard-fork switch block (nil = no fork)
DAOForkSupport bool `json:"daoForkSupport,omitempty"` // Whether the nodes supports or opposes the DAO hard-fork
// EIP150 implements the Gas price changes (https://github.com/ethereum/EIPs/issues/150)
EIP150Block *big.Int `json:"eip150Block"` // EIP150 HF block (nil = no fork)
EIP150Hash common.Hash `json:"eip150Hash"` // EIP150 HF hash (fast sync aid)
EIP150Block *big.Int `json:"eip150Block,omitempty"` // EIP150 HF block (nil = no fork)
EIP150Hash common.Hash `json:"eip150Hash,omitempty"` // EIP150 HF hash (fast sync aid)
EIP155Block *big.Int `json:"eip155Block"` // EIP155 HF block
EIP158Block *big.Int `json:"eip158Block"` // EIP158 HF block
EIP155Block *big.Int `json:"eip155Block,omitempty"` // EIP155 HF block
EIP158Block *big.Int `json:"eip158Block,omitempty"` // EIP158 HF block
// Various consensus engines
Ethash *EthashConfig `json:"ethash,omitempty"`
Clique *CliqueConfig `json:"clique,omitempty"`
}
// EthashConfig is the consensus engine configs for proof-of-work based sealing.
type EthashConfig struct{}
// String implements the stringer interface, returning the consensus engine details.
func (c *EthashConfig) String() string {
return "ethash"
}
// CliqueConfig is the consensus engine configs for proof-of-authority based sealing.
type CliqueConfig struct {
Period uint64 `json:"period"` // Number of seconds between blocks to enforce
Epoch uint64 `json:"epoch"` // Epoch length to reset votes and checkpoint
}
// String implements the stringer interface, returning the consensus engine details.
func (c *CliqueConfig) String() string {
return "clique"
}
// String implements the fmt.Stringer interface.
func (c *ChainConfig) String() string {
return fmt.Sprintf("{ChainID: %v Homestead: %v DAO: %v DAOSupport: %v EIP150: %v EIP155: %v EIP158: %v}",
var engine interface{}
switch {
case c.Ethash != nil:
engine = c.Ethash
case c.Clique != nil:
engine = c.Clique
default:
engine = "unknown"
}
return fmt.Sprintf("{ChainID: %v Homestead: %v DAO: %v DAOSupport: %v EIP150: %v EIP155: %v EIP158: %v Engine: %v}",
c.ChainId,
c.HomesteadBlock,
c.DAOForkBlock,
......@@ -91,6 +125,7 @@ func (c *ChainConfig) String() string {
c.EIP150Block,
c.EIP155Block,
c.EIP158Block,
engine,
)
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment