github.com/matthieu/go-ethereum@v1.13.2/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/matthieu/go-ethereum/common"
    29  	"github.com/matthieu/go-ethereum/common/hexutil"
    30  	"github.com/matthieu/go-ethereum/common/math"
    31  	"github.com/matthieu/go-ethereum/core/rawdb"
    32  	"github.com/matthieu/go-ethereum/core/state"
    33  	"github.com/matthieu/go-ethereum/core/types"
    34  	"github.com/matthieu/go-ethereum/crypto"
    35  	"github.com/matthieu/go-ethereum/ethdb"
    36  	"github.com/matthieu/go-ethereum/log"
    37  	"github.com/matthieu/go-ethereum/params"
    38  	"github.com/matthieu/go-ethereum/rlp"
    39  )
    40  
    41  //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
    42  //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
    43  
    44  var errGenesisNoConfig = errors.New("genesis has no chain configuration")
    45  
    46  // Genesis specifies the header fields, state of a genesis block. It also defines hard
    47  // fork switch-over blocks through the chain configuration.
    48  type Genesis struct {
    49  	Config     *params.ChainConfig `json:"config"`
    50  	Nonce      uint64              `json:"nonce"`
    51  	Timestamp  uint64              `json:"timestamp"`
    52  	ExtraData  []byte              `json:"extraData"`
    53  	GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
    54  	Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
    55  	Mixhash    common.Hash         `json:"mixHash"`
    56  	Coinbase   common.Address      `json:"coinbase"`
    57  	Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`
    58  
    59  	// These fields are used for consensus tests. Please don't use them
    60  	// in actual genesis blocks.
    61  	Number     uint64      `json:"number"`
    62  	GasUsed    uint64      `json:"gasUsed"`
    63  	ParentHash common.Hash `json:"parentHash"`
    64  }
    65  
    66  // GenesisAlloc specifies the initial state that is part of the genesis block.
    67  type GenesisAlloc map[common.Address]GenesisAccount
    68  
    69  func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
    70  	m := make(map[common.UnprefixedAddress]GenesisAccount)
    71  	if err := json.Unmarshal(data, &m); err != nil {
    72  		return err
    73  	}
    74  	*ga = make(GenesisAlloc)
    75  	for addr, a := range m {
    76  		(*ga)[common.Address(addr)] = a
    77  	}
    78  	return nil
    79  }
    80  
    81  // GenesisAccount is an account in the state of the genesis block.
    82  type GenesisAccount struct {
    83  	Code       []byte                      `json:"code,omitempty"`
    84  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
    85  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
    86  	Nonce      uint64                      `json:"nonce,omitempty"`
    87  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
    88  }
    89  
    90  // field type overrides for gencodec
    91  type genesisSpecMarshaling struct {
    92  	Nonce      math.HexOrDecimal64
    93  	Timestamp  math.HexOrDecimal64
    94  	ExtraData  hexutil.Bytes
    95  	GasLimit   math.HexOrDecimal64
    96  	GasUsed    math.HexOrDecimal64
    97  	Number     math.HexOrDecimal64
    98  	Difficulty *math.HexOrDecimal256
    99  	Alloc      map[common.UnprefixedAddress]GenesisAccount
   100  }
   101  
   102  type genesisAccountMarshaling struct {
   103  	Code       hexutil.Bytes
   104  	Balance    *math.HexOrDecimal256
   105  	Nonce      math.HexOrDecimal64
   106  	Storage    map[storageJSON]storageJSON
   107  	PrivateKey hexutil.Bytes
   108  }
   109  
   110  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   111  // unmarshaling from hex.
   112  type storageJSON common.Hash
   113  
   114  func (h *storageJSON) UnmarshalText(text []byte) error {
   115  	text = bytes.TrimPrefix(text, []byte("0x"))
   116  	if len(text) > 64 {
   117  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   118  	}
   119  	offset := len(h) - len(text)/2 // pad on the left
   120  	if _, err := hex.Decode(h[offset:], text); err != nil {
   121  		fmt.Println(err)
   122  		return fmt.Errorf("invalid hex storage key/value %q", text)
   123  	}
   124  	return nil
   125  }
   126  
   127  func (h storageJSON) MarshalText() ([]byte, error) {
   128  	return hexutil.Bytes(h[:]).MarshalText()
   129  }
   130  
   131  // GenesisMismatchError is raised when trying to overwrite an existing
   132  // genesis block with an incompatible one.
   133  type GenesisMismatchError struct {
   134  	Stored, New common.Hash
   135  }
   136  
   137  func (e *GenesisMismatchError) Error() string {
   138  	return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New)
   139  }
   140  
   141  // SetupGenesisBlock writes or updates the genesis block in db.
   142  // The block that will be used is:
   143  //
   144  //                          genesis == nil       genesis != nil
   145  //                       +------------------------------------------
   146  //     db has no genesis |  main-net default  |  genesis
   147  //     db has genesis    |  from DB           |  genesis (if compatible)
   148  //
   149  // The stored chain configuration will be updated if it is compatible (i.e. does not
   150  // specify a fork block below the local head block). In case of a conflict, the
   151  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   152  //
   153  // The returned chain configuration is never nil.
   154  func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   155  	if genesis != nil && genesis.Config == nil {
   156  		return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
   157  	}
   158  	// Just commit the new block if there is no stored genesis block.
   159  	stored := rawdb.ReadCanonicalHash(db, 0)
   160  	if (stored == common.Hash{}) {
   161  		if genesis == nil {
   162  			log.Info("Writing default main-net genesis block")
   163  			genesis = DefaultGenesisBlock()
   164  		} else {
   165  			log.Info("Writing custom genesis block")
   166  		}
   167  		block, err := genesis.Commit(db)
   168  		if err != nil {
   169  			return genesis.Config, common.Hash{}, err
   170  		}
   171  		return genesis.Config, block.Hash(), nil
   172  	}
   173  
   174  	// We have the genesis block in database(perhaps in ancient database)
   175  	// but the corresponding state is missing.
   176  	header := rawdb.ReadHeader(db, stored, 0)
   177  	if _, err := state.New(header.Root, state.NewDatabaseWithCache(db, 0), nil); err != nil {
   178  		if genesis == nil {
   179  			genesis = DefaultGenesisBlock()
   180  		}
   181  		// Ensure the stored genesis matches with the given one.
   182  		hash := genesis.ToBlock(nil).Hash()
   183  		if hash != stored {
   184  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   185  		}
   186  		block, err := genesis.Commit(db)
   187  		if err != nil {
   188  			return genesis.Config, hash, err
   189  		}
   190  		return genesis.Config, block.Hash(), nil
   191  	}
   192  
   193  	// Check whether the genesis block is already written.
   194  	if genesis != nil {
   195  		hash := genesis.ToBlock(nil).Hash()
   196  		if hash != stored {
   197  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   198  		}
   199  	}
   200  
   201  	// Get the existing chain configuration.
   202  	newcfg := genesis.configOrDefault(stored)
   203  	if err := newcfg.CheckConfigForkOrder(); err != nil {
   204  		return newcfg, common.Hash{}, err
   205  	}
   206  	storedcfg := rawdb.ReadChainConfig(db, stored)
   207  	if storedcfg == nil {
   208  		log.Warn("Found genesis block without chain config")
   209  		rawdb.WriteChainConfig(db, stored, newcfg)
   210  		return newcfg, stored, nil
   211  	}
   212  	// Special case: don't change the existing config of a non-mainnet chain if no new
   213  	// config is supplied. These chains would get AllProtocolChanges (and a compat error)
   214  	// if we just continued here.
   215  	if genesis == nil && stored != params.MainnetGenesisHash {
   216  		return storedcfg, stored, nil
   217  	}
   218  
   219  	// Check config compatibility and write the config. Compatibility errors
   220  	// are returned to the caller unless we're already at block zero.
   221  	height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
   222  	if height == nil {
   223  		return newcfg, stored, fmt.Errorf("missing block number for head header hash")
   224  	}
   225  	compatErr := storedcfg.CheckCompatible(newcfg, *height)
   226  	if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
   227  		return newcfg, stored, compatErr
   228  	}
   229  	rawdb.WriteChainConfig(db, stored, newcfg)
   230  	return newcfg, stored, nil
   231  }
   232  
   233  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   234  	switch {
   235  	case g != nil:
   236  		return g.Config
   237  	case ghash == params.MainnetGenesisHash:
   238  		return params.MainnetChainConfig
   239  	case ghash == params.RopstenGenesisHash:
   240  		return params.RopstenChainConfig
   241  	case ghash == params.RinkebyGenesisHash:
   242  		return params.RinkebyChainConfig
   243  	case ghash == params.GoerliGenesisHash:
   244  		return params.GoerliChainConfig
   245  	case ghash == params.YoloV1GenesisHash:
   246  		return params.YoloV1ChainConfig
   247  	default:
   248  		return params.AllEthashProtocolChanges
   249  	}
   250  }
   251  
   252  // ToBlock creates the genesis block and writes state of a genesis specification
   253  // to the given database (or discards it if nil).
   254  func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
   255  	if db == nil {
   256  		db = rawdb.NewMemoryDatabase()
   257  	}
   258  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(db), nil)
   259  	for addr, account := range g.Alloc {
   260  		statedb.AddBalance(addr, account.Balance)
   261  		statedb.SetCode(addr, account.Code)
   262  		statedb.SetNonce(addr, account.Nonce)
   263  		for key, value := range account.Storage {
   264  			statedb.SetState(addr, key, value)
   265  		}
   266  	}
   267  	root := statedb.IntermediateRoot(false)
   268  	head := &types.Header{
   269  		Number:     new(big.Int).SetUint64(g.Number),
   270  		Nonce:      types.EncodeNonce(g.Nonce),
   271  		Time:       g.Timestamp,
   272  		ParentHash: g.ParentHash,
   273  		Extra:      g.ExtraData,
   274  		GasLimit:   g.GasLimit,
   275  		GasUsed:    g.GasUsed,
   276  		Difficulty: g.Difficulty,
   277  		MixDigest:  g.Mixhash,
   278  		Coinbase:   g.Coinbase,
   279  		Root:       root,
   280  	}
   281  	if g.GasLimit == 0 {
   282  		head.GasLimit = params.GenesisGasLimit
   283  	}
   284  	if g.Difficulty == nil {
   285  		head.Difficulty = params.GenesisDifficulty
   286  	}
   287  	statedb.Commit(false)
   288  	statedb.Database().TrieDB().Commit(root, true, nil)
   289  
   290  	return types.NewBlock(head, nil, nil, nil)
   291  }
   292  
   293  // Commit writes the block and state of a genesis specification to the database.
   294  // The block is committed as the canonical head block.
   295  func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
   296  	block := g.ToBlock(db)
   297  	if block.Number().Sign() != 0 {
   298  		return nil, fmt.Errorf("can't commit genesis block with number > 0")
   299  	}
   300  	config := g.Config
   301  	if config == nil {
   302  		config = params.AllEthashProtocolChanges
   303  	}
   304  	if err := config.CheckConfigForkOrder(); err != nil {
   305  		return nil, err
   306  	}
   307  	rawdb.WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty)
   308  	rawdb.WriteBlock(db, block)
   309  	rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
   310  	rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
   311  	rawdb.WriteHeadBlockHash(db, block.Hash())
   312  	rawdb.WriteHeadFastBlockHash(db, block.Hash())
   313  	rawdb.WriteHeadHeaderHash(db, block.Hash())
   314  	rawdb.WriteChainConfig(db, block.Hash(), config)
   315  	return block, nil
   316  }
   317  
   318  // MustCommit writes the genesis block and state to db, panicking on error.
   319  // The block is committed as the canonical head block.
   320  func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
   321  	block, err := g.Commit(db)
   322  	if err != nil {
   323  		panic(err)
   324  	}
   325  	return block
   326  }
   327  
   328  // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
   329  func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
   330  	g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
   331  	return g.MustCommit(db)
   332  }
   333  
   334  // DefaultGenesisBlock returns the Ethereum main net genesis block.
   335  func DefaultGenesisBlock() *Genesis {
   336  	return &Genesis{
   337  		Config:     params.MainnetChainConfig,
   338  		Nonce:      66,
   339  		ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
   340  		GasLimit:   5000,
   341  		Difficulty: big.NewInt(17179869184),
   342  		Alloc:      decodePrealloc(mainnetAllocData),
   343  	}
   344  }
   345  
   346  // DefaultRopstenGenesisBlock returns the Ropsten network genesis block.
   347  func DefaultRopstenGenesisBlock() *Genesis {
   348  	return &Genesis{
   349  		Config:     params.RopstenChainConfig,
   350  		Nonce:      66,
   351  		ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
   352  		GasLimit:   16777216,
   353  		Difficulty: big.NewInt(1048576),
   354  		Alloc:      decodePrealloc(ropstenAllocData),
   355  	}
   356  }
   357  
   358  // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
   359  func DefaultRinkebyGenesisBlock() *Genesis {
   360  	return &Genesis{
   361  		Config:     params.RinkebyChainConfig,
   362  		Timestamp:  1492009146,
   363  		ExtraData:  hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   364  		GasLimit:   4700000,
   365  		Difficulty: big.NewInt(1),
   366  		Alloc:      decodePrealloc(rinkebyAllocData),
   367  	}
   368  }
   369  
   370  // DefaultGoerliGenesisBlock returns the Görli network genesis block.
   371  func DefaultGoerliGenesisBlock() *Genesis {
   372  	return &Genesis{
   373  		Config:     params.GoerliChainConfig,
   374  		Timestamp:  1548854791,
   375  		ExtraData:  hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   376  		GasLimit:   10485760,
   377  		Difficulty: big.NewInt(1),
   378  		Alloc:      decodePrealloc(goerliAllocData),
   379  	}
   380  }
   381  
   382  func DefaultYoloV1GenesisBlock() *Genesis {
   383  	return &Genesis{
   384  		Config:     params.YoloV1ChainConfig,
   385  		Timestamp:  0x5ed754f1,
   386  		ExtraData:  hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000008a37866fd3627c9205a37c8685666f32ec07bb1b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   387  		GasLimit:   0x47b760,
   388  		Difficulty: big.NewInt(1),
   389  		Alloc:      decodePrealloc(yoloV1AllocData),
   390  	}
   391  }
   392  
   393  // DeveloperGenesisBlock returns the 'geth --dev' genesis block.
   394  func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
   395  	// Override the default period to the user requested one
   396  	config := *params.AllCliqueProtocolChanges
   397  	config.Clique.Period = period
   398  
   399  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   400  	return &Genesis{
   401  		Config:     &config,
   402  		ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...),
   403  		GasLimit:   11500000,
   404  		Difficulty: big.NewInt(1),
   405  		Alloc: map[common.Address]GenesisAccount{
   406  			common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   407  			common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   408  			common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   409  			common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   410  			common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   411  			common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   412  			common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   413  			common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   414  			common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b
   415  			faucet:                           {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
   416  		},
   417  	}
   418  }
   419  
   420  func decodePrealloc(data string) GenesisAlloc {
   421  	var p []struct{ Addr, Balance *big.Int }
   422  	if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
   423  		panic(err)
   424  	}
   425  	ga := make(GenesisAlloc, len(p))
   426  	for _, account := range p {
   427  		ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
   428  	}
   429  	return ga
   430  }