github.com/4000d/go-ethereum@v1.8.2-0.20180223170251-423c8bb1d821/core/genesis.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"strings"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/common/hexutil"
    30  	"github.com/ethereum/go-ethereum/common/math"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/params"
    36  	"github.com/ethereum/go-ethereum/rlp"
    37  )
    38  
    39  //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
    40  //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
    41  
    42  var errGenesisNoConfig = errors.New("genesis has no chain configuration")
    43  
    44  // Genesis specifies the header fields, state of a genesis block. It also defines hard
    45  // fork switch-over blocks through the chain configuration.
    46  type Genesis struct {
    47  	Config     *params.ChainConfig `json:"config"`
    48  	Nonce      uint64              `json:"nonce"`
    49  	Timestamp  uint64              `json:"timestamp"`
    50  	ExtraData  []byte              `json:"extraData"`
    51  	GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
    52  	Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
    53  	Mixhash    common.Hash         `json:"mixHash"`
    54  	Coinbase   common.Address      `json:"coinbase"`
    55  	Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`
    56  
    57  	// These fields are used for consensus tests. Please don't use them
    58  	// in actual genesis blocks.
    59  	Number     uint64      `json:"number"`
    60  	GasUsed    uint64      `json:"gasUsed"`
    61  	ParentHash common.Hash `json:"parentHash"`
    62  }
    63  
    64  // GenesisAlloc specifies the initial state that is part of the genesis block.
    65  type GenesisAlloc map[common.Address]GenesisAccount
    66  
    67  func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
    68  	m := make(map[common.UnprefixedAddress]GenesisAccount)
    69  	if err := json.Unmarshal(data, &m); err != nil {
    70  		return err
    71  	}
    72  	*ga = make(GenesisAlloc)
    73  	for addr, a := range m {
    74  		(*ga)[common.Address(addr)] = a
    75  	}
    76  	return nil
    77  }
    78  
    79  // GenesisAccount is an account in the state of the genesis block.
    80  type GenesisAccount struct {
    81  	Code       []byte                      `json:"code,omitempty"`
    82  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
    83  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
    84  	Nonce      uint64                      `json:"nonce,omitempty"`
    85  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
    86  }
    87  
    88  // field type overrides for gencodec
    89  type genesisSpecMarshaling struct {
    90  	Nonce      math.HexOrDecimal64
    91  	Timestamp  math.HexOrDecimal64
    92  	ExtraData  hexutil.Bytes
    93  	GasLimit   math.HexOrDecimal64
    94  	GasUsed    math.HexOrDecimal64
    95  	Number     math.HexOrDecimal64
    96  	Difficulty *math.HexOrDecimal256
    97  	Alloc      map[common.UnprefixedAddress]GenesisAccount
    98  }
    99  
   100  type genesisAccountMarshaling struct {
   101  	Code       hexutil.Bytes
   102  	Balance    *math.HexOrDecimal256
   103  	Nonce      math.HexOrDecimal64
   104  	Storage    map[storageJSON]storageJSON
   105  	PrivateKey hexutil.Bytes
   106  }
   107  
   108  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   109  // unmarshaling from hex.
   110  type storageJSON common.Hash
   111  
   112  func (h *storageJSON) UnmarshalText(text []byte) error {
   113  	text = bytes.TrimPrefix(text, []byte("0x"))
   114  	if len(text) > 64 {
   115  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   116  	}
   117  	offset := len(h) - len(text)/2 // pad on the left
   118  	if _, err := hex.Decode(h[offset:], text); err != nil {
   119  		fmt.Println(err)
   120  		return fmt.Errorf("invalid hex storage key/value %q", text)
   121  	}
   122  	return nil
   123  }
   124  
   125  func (h storageJSON) MarshalText() ([]byte, error) {
   126  	return hexutil.Bytes(h[:]).MarshalText()
   127  }
   128  
   129  // GenesisMismatchError is raised when trying to overwrite an existing
   130  // genesis block with an incompatible one.
   131  type GenesisMismatchError struct {
   132  	Stored, New common.Hash
   133  }
   134  
   135  func (e *GenesisMismatchError) Error() string {
   136  	return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8])
   137  }
   138  
   139  // SetupGenesisBlock writes or updates the genesis block in db.
   140  // The block that will be used is:
   141  //
   142  //                          genesis == nil       genesis != nil
   143  //                       +------------------------------------------
   144  //     db has no genesis |  main-net default  |  genesis
   145  //     db has genesis    |  from DB           |  genesis (if compatible)
   146  //
   147  // The stored chain configuration will be updated if it is compatible (i.e. does not
   148  // specify a fork block below the local head block). In case of a conflict, the
   149  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   150  //
   151  // The returned chain configuration is never nil.
   152  func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   153  	if genesis != nil && genesis.Config == nil {
   154  		return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
   155  	}
   156  
   157  	// Just commit the new block if there is no stored genesis block.
   158  	stored := GetCanonicalHash(db, 0)
   159  	if (stored == common.Hash{}) {
   160  		if genesis == nil {
   161  			log.Info("Writing default main-net genesis block")
   162  			genesis = DefaultGenesisBlock()
   163  		} else {
   164  			log.Info("Writing custom genesis block")
   165  		}
   166  		block, err := genesis.Commit(db)
   167  		return genesis.Config, block.Hash(), err
   168  	}
   169  
   170  	// Check whether the genesis block is already written.
   171  	if genesis != nil {
   172  		hash := genesis.ToBlock(nil).Hash()
   173  		if hash != stored {
   174  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   175  		}
   176  	}
   177  
   178  	// Get the existing chain configuration.
   179  	newcfg := genesis.configOrDefault(stored)
   180  	storedcfg, err := GetChainConfig(db, stored)
   181  	if err != nil {
   182  		if err == ErrChainConfigNotFound {
   183  			// This case happens if a genesis write was interrupted.
   184  			log.Warn("Found genesis block without chain config")
   185  			err = WriteChainConfig(db, stored, newcfg)
   186  		}
   187  		return newcfg, stored, err
   188  	}
   189  	// Special case: don't change the existing config of a non-mainnet chain if no new
   190  	// config is supplied. These chains would get AllProtocolChanges (and a compat error)
   191  	// if we just continued here.
   192  	if genesis == nil && stored != params.MainnetGenesisHash {
   193  		return storedcfg, stored, nil
   194  	}
   195  
   196  	// Check config compatibility and write the config. Compatibility errors
   197  	// are returned to the caller unless we're already at block zero.
   198  	height := GetBlockNumber(db, GetHeadHeaderHash(db))
   199  	if height == missingNumber {
   200  		return newcfg, stored, fmt.Errorf("missing block number for head header hash")
   201  	}
   202  	compatErr := storedcfg.CheckCompatible(newcfg, height)
   203  	if compatErr != nil && height != 0 && compatErr.RewindTo != 0 {
   204  		return newcfg, stored, compatErr
   205  	}
   206  	return newcfg, stored, WriteChainConfig(db, stored, newcfg)
   207  }
   208  
   209  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   210  	switch {
   211  	case g != nil:
   212  		return g.Config
   213  	case ghash == params.MainnetGenesisHash:
   214  		return params.MainnetChainConfig
   215  	case ghash == params.TestnetGenesisHash:
   216  		return params.TestnetChainConfig
   217  	default:
   218  		return params.AllEthashProtocolChanges
   219  	}
   220  }
   221  
   222  // ToBlock creates the genesis block and writes state of a genesis specification
   223  // to the given database (or discards it if nil).
   224  func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
   225  	if db == nil {
   226  		db, _ = ethdb.NewMemDatabase()
   227  	}
   228  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
   229  	for addr, account := range g.Alloc {
   230  		statedb.AddBalance(addr, account.Balance)
   231  		statedb.SetCode(addr, account.Code)
   232  		statedb.SetNonce(addr, account.Nonce)
   233  		for key, value := range account.Storage {
   234  			statedb.SetState(addr, key, value)
   235  		}
   236  	}
   237  	root := statedb.IntermediateRoot(false)
   238  	head := &types.Header{
   239  		Number:     new(big.Int).SetUint64(g.Number),
   240  		Nonce:      types.EncodeNonce(g.Nonce),
   241  		Time:       new(big.Int).SetUint64(g.Timestamp),
   242  		ParentHash: g.ParentHash,
   243  		Extra:      g.ExtraData,
   244  		GasLimit:   g.GasLimit,
   245  		GasUsed:    g.GasUsed,
   246  		Difficulty: g.Difficulty,
   247  		MixDigest:  g.Mixhash,
   248  		Coinbase:   g.Coinbase,
   249  		Root:       root,
   250  	}
   251  	if g.GasLimit == 0 {
   252  		head.GasLimit = params.GenesisGasLimit
   253  	}
   254  	if g.Difficulty == nil {
   255  		head.Difficulty = params.GenesisDifficulty
   256  	}
   257  	statedb.Commit(false)
   258  	statedb.Database().TrieDB().Commit(root, true)
   259  
   260  	return types.NewBlock(head, nil, nil, nil)
   261  }
   262  
   263  // Commit writes the block and state of a genesis specification to the database.
   264  // The block is committed as the canonical head block.
   265  func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
   266  	block := g.ToBlock(db)
   267  	if block.Number().Sign() != 0 {
   268  		return nil, fmt.Errorf("can't commit genesis block with number > 0")
   269  	}
   270  	if err := WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty); err != nil {
   271  		return nil, err
   272  	}
   273  	if err := WriteBlock(db, block); err != nil {
   274  		return nil, err
   275  	}
   276  	if err := WriteBlockReceipts(db, block.Hash(), block.NumberU64(), nil); err != nil {
   277  		return nil, err
   278  	}
   279  	if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil {
   280  		return nil, err
   281  	}
   282  	if err := WriteHeadBlockHash(db, block.Hash()); err != nil {
   283  		return nil, err
   284  	}
   285  	if err := WriteHeadHeaderHash(db, block.Hash()); err != nil {
   286  		return nil, err
   287  	}
   288  	config := g.Config
   289  	if config == nil {
   290  		config = params.AllEthashProtocolChanges
   291  	}
   292  	return block, WriteChainConfig(db, block.Hash(), config)
   293  }
   294  
   295  // MustCommit writes the genesis block and state to db, panicking on error.
   296  // The block is committed as the canonical head block.
   297  func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
   298  	block, err := g.Commit(db)
   299  	if err != nil {
   300  		panic(err)
   301  	}
   302  	return block
   303  }
   304  
   305  // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
   306  func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
   307  	g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
   308  	return g.MustCommit(db)
   309  }
   310  
   311  // DefaultGenesisBlock returns the Ethereum main net genesis block.
   312  func DefaultGenesisBlock() *Genesis {
   313  	return &Genesis{
   314  		Config:     params.MainnetChainConfig,
   315  		Nonce:      66,
   316  		ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
   317  		GasLimit:   5000,
   318  		Difficulty: big.NewInt(17179869184),
   319  		Alloc:      decodePrealloc(mainnetAllocData),
   320  	}
   321  }
   322  
   323  // DefaultTestnetGenesisBlock returns the Ropsten network genesis block.
   324  func DefaultTestnetGenesisBlock() *Genesis {
   325  	return &Genesis{
   326  		Config:     params.TestnetChainConfig,
   327  		Nonce:      66,
   328  		ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
   329  		GasLimit:   16777216,
   330  		Difficulty: big.NewInt(1048576),
   331  		Alloc:      decodePrealloc(testnetAllocData),
   332  	}
   333  }
   334  
   335  // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
   336  func DefaultRinkebyGenesisBlock() *Genesis {
   337  	return &Genesis{
   338  		Config:     params.RinkebyChainConfig,
   339  		Timestamp:  1492009146,
   340  		ExtraData:  hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   341  		GasLimit:   4700000,
   342  		Difficulty: big.NewInt(1),
   343  		Alloc:      decodePrealloc(rinkebyAllocData),
   344  	}
   345  }
   346  
   347  // DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must
   348  // be seeded with the
   349  func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
   350  	// Override the default period to the user requested one
   351  	config := *params.AllCliqueProtocolChanges
   352  	config.Clique.Period = period
   353  
   354  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   355  	return &Genesis{
   356  		Config:     &config,
   357  		ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, 65)...),
   358  		GasLimit:   6283185,
   359  		Difficulty: big.NewInt(1),
   360  		Alloc: map[common.Address]GenesisAccount{
   361  			common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   362  			common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   363  			common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   364  			common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   365  			common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   366  			common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   367  			common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   368  			common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   369  			faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
   370  		},
   371  	}
   372  }
   373  
   374  func decodePrealloc(data string) GenesisAlloc {
   375  	var p []struct{ Addr, Balance *big.Int }
   376  	if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
   377  		panic(err)
   378  	}
   379  	ga := make(GenesisAlloc, len(p))
   380  	for _, account := range p {
   381  		ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
   382  	}
   383  	return ga
   384  }