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