github.com/jimmyx0x/go-ethereum@v1.10.28/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/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/state"
    33  	"github.com/ethereum/go-ethereum/core/types"
    34  	"github.com/ethereum/go-ethereum/crypto"
    35  	"github.com/ethereum/go-ethereum/ethdb"
    36  	"github.com/ethereum/go-ethereum/log"
    37  	"github.com/ethereum/go-ethereum/params"
    38  	"github.com/ethereum/go-ethereum/rlp"
    39  	"github.com/ethereum/go-ethereum/trie"
    40  )
    41  
    42  //go:generate go run github.com/fjl/gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
    43  //go:generate go run github.com/fjl/gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
    44  
    45  var errGenesisNoConfig = errors.New("genesis has no chain configuration")
    46  
    47  // Genesis specifies the header fields, state of a genesis block. It also defines hard
    48  // fork switch-over blocks through the chain configuration.
    49  type Genesis struct {
    50  	Config     *params.ChainConfig `json:"config"`
    51  	Nonce      uint64              `json:"nonce"`
    52  	Timestamp  uint64              `json:"timestamp"`
    53  	ExtraData  []byte              `json:"extraData"`
    54  	GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
    55  	Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
    56  	Mixhash    common.Hash         `json:"mixHash"`
    57  	Coinbase   common.Address      `json:"coinbase"`
    58  	Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`
    59  
    60  	// These fields are used for consensus tests. Please don't use them
    61  	// in actual genesis blocks.
    62  	Number     uint64      `json:"number"`
    63  	GasUsed    uint64      `json:"gasUsed"`
    64  	ParentHash common.Hash `json:"parentHash"`
    65  	BaseFee    *big.Int    `json:"baseFeePerGas"`
    66  }
    67  
    68  func ReadGenesis(db ethdb.Database) (*Genesis, error) {
    69  	var genesis Genesis
    70  	stored := rawdb.ReadCanonicalHash(db, 0)
    71  	if (stored == common.Hash{}) {
    72  		return nil, fmt.Errorf("invalid genesis hash in database: %x", stored)
    73  	}
    74  	blob := rawdb.ReadGenesisStateSpec(db, stored)
    75  	if blob == nil {
    76  		return nil, fmt.Errorf("genesis state missing from db")
    77  	}
    78  	if len(blob) != 0 {
    79  		if err := genesis.Alloc.UnmarshalJSON(blob); err != nil {
    80  			return nil, fmt.Errorf("could not unmarshal genesis state json: %s", err)
    81  		}
    82  	}
    83  	genesis.Config = rawdb.ReadChainConfig(db, stored)
    84  	if genesis.Config == nil {
    85  		return nil, fmt.Errorf("genesis config missing from db")
    86  	}
    87  	genesisBlock := rawdb.ReadBlock(db, stored, 0)
    88  	if genesisBlock == nil {
    89  		return nil, fmt.Errorf("genesis block missing from db")
    90  	}
    91  	genesisHeader := genesisBlock.Header()
    92  	genesis.Nonce = genesisHeader.Nonce.Uint64()
    93  	genesis.Timestamp = genesisHeader.Time
    94  	genesis.ExtraData = genesisHeader.Extra
    95  	genesis.GasLimit = genesisHeader.GasLimit
    96  	genesis.Difficulty = genesisHeader.Difficulty
    97  	genesis.Mixhash = genesisHeader.MixDigest
    98  	genesis.Coinbase = genesisHeader.Coinbase
    99  
   100  	return &genesis, nil
   101  }
   102  
   103  // GenesisAlloc specifies the initial state that is part of the genesis block.
   104  type GenesisAlloc map[common.Address]GenesisAccount
   105  
   106  func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
   107  	m := make(map[common.UnprefixedAddress]GenesisAccount)
   108  	if err := json.Unmarshal(data, &m); err != nil {
   109  		return err
   110  	}
   111  	*ga = make(GenesisAlloc)
   112  	for addr, a := range m {
   113  		(*ga)[common.Address(addr)] = a
   114  	}
   115  	return nil
   116  }
   117  
   118  // deriveHash computes the state root according to the genesis specification.
   119  func (ga *GenesisAlloc) deriveHash() (common.Hash, error) {
   120  	// Create an ephemeral in-memory database for computing hash,
   121  	// all the derived states will be discarded to not pollute disk.
   122  	db := state.NewDatabase(rawdb.NewMemoryDatabase())
   123  	statedb, err := state.New(common.Hash{}, db, nil)
   124  	if err != nil {
   125  		return common.Hash{}, err
   126  	}
   127  	for addr, account := range *ga {
   128  		statedb.AddBalance(addr, account.Balance)
   129  		statedb.SetCode(addr, account.Code)
   130  		statedb.SetNonce(addr, account.Nonce)
   131  		for key, value := range account.Storage {
   132  			statedb.SetState(addr, key, value)
   133  		}
   134  	}
   135  	return statedb.Commit(false)
   136  }
   137  
   138  // flush is very similar with deriveHash, but the main difference is
   139  // all the generated states will be persisted into the given database.
   140  // Also, the genesis state specification will be flushed as well.
   141  func (ga *GenesisAlloc) flush(db ethdb.Database, triedb *trie.Database) error {
   142  	statedb, err := state.New(common.Hash{}, state.NewDatabaseWithNodeDB(db, triedb), nil)
   143  	if err != nil {
   144  		return err
   145  	}
   146  	for addr, account := range *ga {
   147  		statedb.AddBalance(addr, account.Balance)
   148  		statedb.SetCode(addr, account.Code)
   149  		statedb.SetNonce(addr, account.Nonce)
   150  		for key, value := range account.Storage {
   151  			statedb.SetState(addr, key, value)
   152  		}
   153  	}
   154  	root, err := statedb.Commit(false)
   155  	if err != nil {
   156  		return err
   157  	}
   158  	// Commit newly generated states into disk if it's not empty.
   159  	if root != types.EmptyRootHash {
   160  		if err := triedb.Commit(root, true, nil); err != nil {
   161  			return err
   162  		}
   163  	}
   164  	// Marshal the genesis state specification and persist.
   165  	blob, err := json.Marshal(ga)
   166  	if err != nil {
   167  		return err
   168  	}
   169  	rawdb.WriteGenesisStateSpec(db, root, blob)
   170  	return nil
   171  }
   172  
   173  // CommitGenesisState loads the stored genesis state with the given block
   174  // hash and commits it into the provided trie database.
   175  func CommitGenesisState(db ethdb.Database, triedb *trie.Database, hash common.Hash) error {
   176  	var alloc GenesisAlloc
   177  	blob := rawdb.ReadGenesisStateSpec(db, hash)
   178  	if len(blob) != 0 {
   179  		if err := alloc.UnmarshalJSON(blob); err != nil {
   180  			return err
   181  		}
   182  	} else {
   183  		// Genesis allocation is missing and there are several possibilities:
   184  		// the node is legacy which doesn't persist the genesis allocation or
   185  		// the persisted allocation is just lost.
   186  		// - supported networks(mainnet, testnets), recover with defined allocations
   187  		// - private network, can't recover
   188  		var genesis *Genesis
   189  		switch hash {
   190  		case params.MainnetGenesisHash:
   191  			genesis = DefaultGenesisBlock()
   192  		case params.RopstenGenesisHash:
   193  			genesis = DefaultRopstenGenesisBlock()
   194  		case params.RinkebyGenesisHash:
   195  			genesis = DefaultRinkebyGenesisBlock()
   196  		case params.GoerliGenesisHash:
   197  			genesis = DefaultGoerliGenesisBlock()
   198  		case params.SepoliaGenesisHash:
   199  			genesis = DefaultSepoliaGenesisBlock()
   200  		}
   201  		if genesis != nil {
   202  			alloc = genesis.Alloc
   203  		} else {
   204  			return errors.New("not found")
   205  		}
   206  	}
   207  	return alloc.flush(db, triedb)
   208  }
   209  
   210  // GenesisAccount is an account in the state of the genesis block.
   211  type GenesisAccount struct {
   212  	Code       []byte                      `json:"code,omitempty"`
   213  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
   214  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
   215  	Nonce      uint64                      `json:"nonce,omitempty"`
   216  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
   217  }
   218  
   219  // field type overrides for gencodec
   220  type genesisSpecMarshaling struct {
   221  	Nonce      math.HexOrDecimal64
   222  	Timestamp  math.HexOrDecimal64
   223  	ExtraData  hexutil.Bytes
   224  	GasLimit   math.HexOrDecimal64
   225  	GasUsed    math.HexOrDecimal64
   226  	Number     math.HexOrDecimal64
   227  	Difficulty *math.HexOrDecimal256
   228  	BaseFee    *math.HexOrDecimal256
   229  	Alloc      map[common.UnprefixedAddress]GenesisAccount
   230  }
   231  
   232  type genesisAccountMarshaling struct {
   233  	Code       hexutil.Bytes
   234  	Balance    *math.HexOrDecimal256
   235  	Nonce      math.HexOrDecimal64
   236  	Storage    map[storageJSON]storageJSON
   237  	PrivateKey hexutil.Bytes
   238  }
   239  
   240  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   241  // unmarshaling from hex.
   242  type storageJSON common.Hash
   243  
   244  func (h *storageJSON) UnmarshalText(text []byte) error {
   245  	text = bytes.TrimPrefix(text, []byte("0x"))
   246  	if len(text) > 64 {
   247  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   248  	}
   249  	offset := len(h) - len(text)/2 // pad on the left
   250  	if _, err := hex.Decode(h[offset:], text); err != nil {
   251  		return fmt.Errorf("invalid hex storage key/value %q", text)
   252  	}
   253  	return nil
   254  }
   255  
   256  func (h storageJSON) MarshalText() ([]byte, error) {
   257  	return hexutil.Bytes(h[:]).MarshalText()
   258  }
   259  
   260  // GenesisMismatchError is raised when trying to overwrite an existing
   261  // genesis block with an incompatible one.
   262  type GenesisMismatchError struct {
   263  	Stored, New common.Hash
   264  }
   265  
   266  func (e *GenesisMismatchError) Error() string {
   267  	return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New)
   268  }
   269  
   270  // ChainOverrides contains the changes to chain config.
   271  type ChainOverrides struct {
   272  	OverrideShanghai *big.Int
   273  }
   274  
   275  // SetupGenesisBlock writes or updates the genesis block in db.
   276  // The block that will be used is:
   277  //
   278  //	                     genesis == nil       genesis != nil
   279  //	                  +------------------------------------------
   280  //	db has no genesis |  main-net default  |  genesis
   281  //	db has genesis    |  from DB           |  genesis (if compatible)
   282  //
   283  // The stored chain configuration will be updated if it is compatible (i.e. does not
   284  // specify a fork block below the local head block). In case of a conflict, the
   285  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   286  //
   287  // The returned chain configuration is never nil.
   288  func SetupGenesisBlock(db ethdb.Database, triedb *trie.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   289  	return SetupGenesisBlockWithOverride(db, triedb, genesis, nil)
   290  }
   291  
   292  func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *trie.Database, genesis *Genesis, overrides *ChainOverrides) (*params.ChainConfig, common.Hash, error) {
   293  	if genesis != nil && genesis.Config == nil {
   294  		return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
   295  	}
   296  	applyOverrides := func(config *params.ChainConfig) {
   297  		if config != nil {
   298  			if overrides != nil && overrides.OverrideShanghai != nil {
   299  				config.ShanghaiTime = overrides.OverrideShanghai
   300  			}
   301  		}
   302  	}
   303  	// Just commit the new block if there is no stored genesis block.
   304  	stored := rawdb.ReadCanonicalHash(db, 0)
   305  	if (stored == common.Hash{}) {
   306  		if genesis == nil {
   307  			log.Info("Writing default main-net genesis block")
   308  			genesis = DefaultGenesisBlock()
   309  		} else {
   310  			log.Info("Writing custom genesis block")
   311  		}
   312  		block, err := genesis.Commit(db, triedb)
   313  		if err != nil {
   314  			return genesis.Config, common.Hash{}, err
   315  		}
   316  		applyOverrides(genesis.Config)
   317  		return genesis.Config, block.Hash(), nil
   318  	}
   319  	// We have the genesis block in database(perhaps in ancient database)
   320  	// but the corresponding state is missing.
   321  	header := rawdb.ReadHeader(db, stored, 0)
   322  	if _, err := state.New(header.Root, state.NewDatabaseWithNodeDB(db, triedb), nil); err != nil {
   323  		if genesis == nil {
   324  			genesis = DefaultGenesisBlock()
   325  		}
   326  		// Ensure the stored genesis matches with the given one.
   327  		hash := genesis.ToBlock().Hash()
   328  		if hash != stored {
   329  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   330  		}
   331  		block, err := genesis.Commit(db, triedb)
   332  		if err != nil {
   333  			return genesis.Config, hash, err
   334  		}
   335  		applyOverrides(genesis.Config)
   336  		return genesis.Config, block.Hash(), nil
   337  	}
   338  	// Check whether the genesis block is already written.
   339  	if genesis != nil {
   340  		hash := genesis.ToBlock().Hash()
   341  		if hash != stored {
   342  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   343  		}
   344  	}
   345  	// Get the existing chain configuration.
   346  	newcfg := genesis.configOrDefault(stored)
   347  	applyOverrides(newcfg)
   348  	if err := newcfg.CheckConfigForkOrder(); err != nil {
   349  		return newcfg, common.Hash{}, err
   350  	}
   351  	storedcfg := rawdb.ReadChainConfig(db, stored)
   352  	if storedcfg == nil {
   353  		log.Warn("Found genesis block without chain config")
   354  		rawdb.WriteChainConfig(db, stored, newcfg)
   355  		return newcfg, stored, nil
   356  	}
   357  	storedData, _ := json.Marshal(storedcfg)
   358  	// Special case: if a private network is being used (no genesis and also no
   359  	// mainnet hash in the database), we must not apply the `configOrDefault`
   360  	// chain config as that would be AllProtocolChanges (applying any new fork
   361  	// on top of an existing private network genesis block). In that case, only
   362  	// apply the overrides.
   363  	if genesis == nil && stored != params.MainnetGenesisHash {
   364  		newcfg = storedcfg
   365  		applyOverrides(newcfg)
   366  	}
   367  	// Check config compatibility and write the config. Compatibility errors
   368  	// are returned to the caller unless we're already at block zero.
   369  	head := rawdb.ReadHeadHeader(db)
   370  	if head == nil {
   371  		return newcfg, stored, fmt.Errorf("missing head header")
   372  	}
   373  	compatErr := storedcfg.CheckCompatible(newcfg, head.Number.Uint64(), head.Time)
   374  	if compatErr != nil && ((head.Number.Uint64() != 0 && compatErr.RewindToBlock != 0) || (head.Time != 0 && compatErr.RewindToTime != 0)) {
   375  		return newcfg, stored, compatErr
   376  	}
   377  	// Don't overwrite if the old is identical to the new
   378  	if newData, _ := json.Marshal(newcfg); !bytes.Equal(storedData, newData) {
   379  		rawdb.WriteChainConfig(db, stored, newcfg)
   380  	}
   381  	return newcfg, stored, nil
   382  }
   383  
   384  // LoadCliqueConfig loads the stored clique config if the chain config
   385  // is already present in database, otherwise, return the config in the
   386  // provided genesis specification. Note the returned clique config can
   387  // be nil if we are not in the clique network.
   388  func LoadCliqueConfig(db ethdb.Database, genesis *Genesis) (*params.CliqueConfig, error) {
   389  	// Load the stored chain config from the database. It can be nil
   390  	// in case the database is empty. Notably, we only care about the
   391  	// chain config corresponds to the canonical chain.
   392  	stored := rawdb.ReadCanonicalHash(db, 0)
   393  	if stored != (common.Hash{}) {
   394  		storedcfg := rawdb.ReadChainConfig(db, stored)
   395  		if storedcfg != nil {
   396  			return storedcfg.Clique, nil
   397  		}
   398  	}
   399  	// Load the clique config from the provided genesis specification.
   400  	if genesis != nil {
   401  		// Reject invalid genesis spec without valid chain config
   402  		if genesis.Config == nil {
   403  			return nil, errGenesisNoConfig
   404  		}
   405  		// If the canonical genesis header is present, but the chain
   406  		// config is missing(initialize the empty leveldb with an
   407  		// external ancient chain segment), ensure the provided genesis
   408  		// is matched.
   409  		if stored != (common.Hash{}) && genesis.ToBlock().Hash() != stored {
   410  			return nil, &GenesisMismatchError{stored, genesis.ToBlock().Hash()}
   411  		}
   412  		return genesis.Config.Clique, nil
   413  	}
   414  	// There is no stored chain config and no new config provided,
   415  	// In this case the default chain config(mainnet) will be used,
   416  	// namely ethash is the specified consensus engine, return nil.
   417  	return nil, nil
   418  }
   419  
   420  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   421  	switch {
   422  	case g != nil:
   423  		return g.Config
   424  	case ghash == params.MainnetGenesisHash:
   425  		return params.MainnetChainConfig
   426  	case ghash == params.RopstenGenesisHash:
   427  		return params.RopstenChainConfig
   428  	case ghash == params.SepoliaGenesisHash:
   429  		return params.SepoliaChainConfig
   430  	case ghash == params.RinkebyGenesisHash:
   431  		return params.RinkebyChainConfig
   432  	case ghash == params.GoerliGenesisHash:
   433  		return params.GoerliChainConfig
   434  	case ghash == params.KilnGenesisHash:
   435  		return DefaultKilnGenesisBlock().Config
   436  	default:
   437  		return params.AllEthashProtocolChanges
   438  	}
   439  }
   440  
   441  // ToBlock returns the genesis block according to genesis specification.
   442  func (g *Genesis) ToBlock() *types.Block {
   443  	root, err := g.Alloc.deriveHash()
   444  	if err != nil {
   445  		panic(err)
   446  	}
   447  	head := &types.Header{
   448  		Number:     new(big.Int).SetUint64(g.Number),
   449  		Nonce:      types.EncodeNonce(g.Nonce),
   450  		Time:       g.Timestamp,
   451  		ParentHash: g.ParentHash,
   452  		Extra:      g.ExtraData,
   453  		GasLimit:   g.GasLimit,
   454  		GasUsed:    g.GasUsed,
   455  		BaseFee:    g.BaseFee,
   456  		Difficulty: g.Difficulty,
   457  		MixDigest:  g.Mixhash,
   458  		Coinbase:   g.Coinbase,
   459  		Root:       root,
   460  	}
   461  	if g.GasLimit == 0 {
   462  		head.GasLimit = params.GenesisGasLimit
   463  	}
   464  	if g.Difficulty == nil && g.Mixhash == (common.Hash{}) {
   465  		head.Difficulty = params.GenesisDifficulty
   466  	}
   467  	if g.Config != nil && g.Config.IsLondon(common.Big0) {
   468  		if g.BaseFee != nil {
   469  			head.BaseFee = g.BaseFee
   470  		} else {
   471  			head.BaseFee = new(big.Int).SetUint64(params.InitialBaseFee)
   472  		}
   473  	}
   474  	return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil))
   475  }
   476  
   477  // Commit writes the block and state of a genesis specification to the database.
   478  // The block is committed as the canonical head block.
   479  func (g *Genesis) Commit(db ethdb.Database, triedb *trie.Database) (*types.Block, error) {
   480  	block := g.ToBlock()
   481  	if block.Number().Sign() != 0 {
   482  		return nil, errors.New("can't commit genesis block with number > 0")
   483  	}
   484  	config := g.Config
   485  	if config == nil {
   486  		config = params.AllEthashProtocolChanges
   487  	}
   488  	if err := config.CheckConfigForkOrder(); err != nil {
   489  		return nil, err
   490  	}
   491  	if config.Clique != nil && len(block.Extra()) < 32+crypto.SignatureLength {
   492  		return nil, errors.New("can't start clique chain without signers")
   493  	}
   494  	// All the checks has passed, flush the states derived from the genesis
   495  	// specification as well as the specification itself into the provided
   496  	// database.
   497  	if err := g.Alloc.flush(db, triedb); err != nil {
   498  		return nil, err
   499  	}
   500  	rawdb.WriteTd(db, block.Hash(), block.NumberU64(), block.Difficulty())
   501  	rawdb.WriteBlock(db, block)
   502  	rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
   503  	rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
   504  	rawdb.WriteHeadBlockHash(db, block.Hash())
   505  	rawdb.WriteHeadFastBlockHash(db, block.Hash())
   506  	rawdb.WriteHeadHeaderHash(db, block.Hash())
   507  	rawdb.WriteChainConfig(db, block.Hash(), config)
   508  	return block, nil
   509  }
   510  
   511  // MustCommit writes the genesis block and state to db, panicking on error.
   512  // The block is committed as the canonical head block.
   513  // Note the state changes will be committed in hash-based scheme, use Commit
   514  // if path-scheme is preferred.
   515  func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
   516  	block, err := g.Commit(db, trie.NewDatabase(db))
   517  	if err != nil {
   518  		panic(err)
   519  	}
   520  	return block
   521  }
   522  
   523  // DefaultGenesisBlock returns the Ethereum main net genesis block.
   524  func DefaultGenesisBlock() *Genesis {
   525  	return &Genesis{
   526  		Config:     params.MainnetChainConfig,
   527  		Nonce:      66,
   528  		ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
   529  		GasLimit:   5000,
   530  		Difficulty: big.NewInt(17179869184),
   531  		Alloc:      decodePrealloc(mainnetAllocData),
   532  	}
   533  }
   534  
   535  // DefaultRopstenGenesisBlock returns the Ropsten network genesis block.
   536  func DefaultRopstenGenesisBlock() *Genesis {
   537  	return &Genesis{
   538  		Config:     params.RopstenChainConfig,
   539  		Nonce:      66,
   540  		ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
   541  		GasLimit:   16777216,
   542  		Difficulty: big.NewInt(1048576),
   543  		Alloc:      decodePrealloc(ropstenAllocData),
   544  	}
   545  }
   546  
   547  // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
   548  func DefaultRinkebyGenesisBlock() *Genesis {
   549  	return &Genesis{
   550  		Config:     params.RinkebyChainConfig,
   551  		Timestamp:  1492009146,
   552  		ExtraData:  hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   553  		GasLimit:   4700000,
   554  		Difficulty: big.NewInt(1),
   555  		Alloc:      decodePrealloc(rinkebyAllocData),
   556  	}
   557  }
   558  
   559  // DefaultGoerliGenesisBlock returns the Görli network genesis block.
   560  func DefaultGoerliGenesisBlock() *Genesis {
   561  	return &Genesis{
   562  		Config:     params.GoerliChainConfig,
   563  		Timestamp:  1548854791,
   564  		ExtraData:  hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   565  		GasLimit:   10485760,
   566  		Difficulty: big.NewInt(1),
   567  		Alloc:      decodePrealloc(goerliAllocData),
   568  	}
   569  }
   570  
   571  // DefaultSepoliaGenesisBlock returns the Sepolia network genesis block.
   572  func DefaultSepoliaGenesisBlock() *Genesis {
   573  	return &Genesis{
   574  		Config:     params.SepoliaChainConfig,
   575  		Nonce:      0,
   576  		ExtraData:  []byte("Sepolia, Athens, Attica, Greece!"),
   577  		GasLimit:   0x1c9c380,
   578  		Difficulty: big.NewInt(0x20000),
   579  		Timestamp:  1633267481,
   580  		Alloc:      decodePrealloc(sepoliaAllocData),
   581  	}
   582  }
   583  
   584  // DefaultKilnGenesisBlock returns the kiln network genesis block.
   585  func DefaultKilnGenesisBlock() *Genesis {
   586  	g := new(Genesis)
   587  	reader := strings.NewReader(KilnAllocData)
   588  	if err := json.NewDecoder(reader).Decode(g); err != nil {
   589  		panic(err)
   590  	}
   591  	return g
   592  }
   593  
   594  // DeveloperGenesisBlock returns the 'geth --dev' genesis block.
   595  func DeveloperGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *Genesis {
   596  	// Override the default period to the user requested one
   597  	config := *params.AllCliqueProtocolChanges
   598  	config.Clique = &params.CliqueConfig{
   599  		Period: period,
   600  		Epoch:  config.Clique.Epoch,
   601  	}
   602  
   603  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   604  	return &Genesis{
   605  		Config:     &config,
   606  		ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...),
   607  		GasLimit:   gasLimit,
   608  		BaseFee:    big.NewInt(params.InitialBaseFee),
   609  		Difficulty: big.NewInt(1),
   610  		Alloc: map[common.Address]GenesisAccount{
   611  			common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   612  			common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   613  			common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   614  			common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   615  			common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   616  			common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   617  			common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   618  			common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   619  			common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b
   620  			faucet:                           {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
   621  		},
   622  	}
   623  }
   624  
   625  func decodePrealloc(data string) GenesisAlloc {
   626  	var p []struct{ Addr, Balance *big.Int }
   627  	if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
   628  		panic(err)
   629  	}
   630  	ga := make(GenesisAlloc, len(p))
   631  	for _, account := range p {
   632  		ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
   633  	}
   634  	return ga
   635  }