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