github.com/VietJr/bor@v1.0.3/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  // flush adds allocated genesis accounts into a fresh new statedb and
    88  // commit the state changes into the given database handler.
    89  func (ga *GenesisAlloc) flush(db ethdb.Database) (common.Hash, error) {
    90  	statedb, err := state.New(common.Hash{}, state.NewDatabase(db), nil)
    91  	if err != nil {
    92  		return common.Hash{}, err
    93  	}
    94  	for addr, account := range *ga {
    95  		statedb.AddBalance(addr, account.Balance)
    96  		statedb.SetCode(addr, account.Code)
    97  		statedb.SetNonce(addr, account.Nonce)
    98  		for key, value := range account.Storage {
    99  			statedb.SetState(addr, key, value)
   100  		}
   101  	}
   102  	root, err := statedb.Commit(false)
   103  	if err != nil {
   104  		return common.Hash{}, err
   105  	}
   106  	err = statedb.Database().TrieDB().Commit(root, true, nil)
   107  	if err != nil {
   108  		return common.Hash{}, err
   109  	}
   110  	return root, nil
   111  }
   112  
   113  // write writes the json marshaled genesis state into database
   114  // with the given block hash as the unique identifier.
   115  func (ga *GenesisAlloc) write(db ethdb.KeyValueWriter, hash common.Hash) error {
   116  	blob, err := json.Marshal(ga)
   117  	if err != nil {
   118  		return err
   119  	}
   120  	rawdb.WriteGenesisState(db, hash, blob)
   121  	return nil
   122  }
   123  
   124  // CommitGenesisState loads the stored genesis state with the given block
   125  // hash and commits them into the given database handler.
   126  func CommitGenesisState(db ethdb.Database, hash common.Hash) error {
   127  	var alloc GenesisAlloc
   128  	blob := rawdb.ReadGenesisState(db, hash)
   129  	if len(blob) != 0 {
   130  		if err := alloc.UnmarshalJSON(blob); err != nil {
   131  			return err
   132  		}
   133  	} else {
   134  		// Genesis allocation is missing and there are several possibilities:
   135  		// the node is legacy which doesn't persist the genesis allocation or
   136  		// the persisted allocation is just lost.
   137  		// - supported networks(mainnet, testnets), recover with defined allocations
   138  		// - private network, can't recover
   139  		var genesis *Genesis
   140  		switch hash {
   141  		case params.MainnetGenesisHash:
   142  			genesis = DefaultGenesisBlock()
   143  		case params.RopstenGenesisHash:
   144  			genesis = DefaultRopstenGenesisBlock()
   145  		case params.RinkebyGenesisHash:
   146  			genesis = DefaultRinkebyGenesisBlock()
   147  		case params.GoerliGenesisHash:
   148  			genesis = DefaultGoerliGenesisBlock()
   149  		case params.SepoliaGenesisHash:
   150  			genesis = DefaultSepoliaGenesisBlock()
   151  		}
   152  		if genesis != nil {
   153  			alloc = genesis.Alloc
   154  		} else {
   155  			return errors.New("not found")
   156  		}
   157  	}
   158  	_, err := alloc.flush(db)
   159  	return err
   160  }
   161  
   162  // GenesisAccount is an account in the state of the genesis block.
   163  type GenesisAccount struct {
   164  	Code       []byte                      `json:"code,omitempty"`
   165  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
   166  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
   167  	Nonce      uint64                      `json:"nonce,omitempty"`
   168  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
   169  }
   170  
   171  // field type overrides for gencodec
   172  type genesisSpecMarshaling struct {
   173  	Nonce      math.HexOrDecimal64
   174  	Timestamp  math.HexOrDecimal64
   175  	ExtraData  hexutil.Bytes
   176  	GasLimit   math.HexOrDecimal64
   177  	GasUsed    math.HexOrDecimal64
   178  	Number     math.HexOrDecimal64
   179  	Difficulty *math.HexOrDecimal256
   180  	BaseFee    *math.HexOrDecimal256
   181  	Alloc      map[common.UnprefixedAddress]GenesisAccount
   182  }
   183  
   184  type genesisAccountMarshaling struct {
   185  	Code       hexutil.Bytes
   186  	Balance    *math.HexOrDecimal256
   187  	Nonce      math.HexOrDecimal64
   188  	Storage    map[storageJSON]storageJSON
   189  	PrivateKey hexutil.Bytes
   190  }
   191  
   192  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   193  // unmarshaling from hex.
   194  type storageJSON common.Hash
   195  
   196  func (h *storageJSON) UnmarshalText(text []byte) error {
   197  	text = bytes.TrimPrefix(text, []byte("0x"))
   198  	if len(text) > 64 {
   199  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   200  	}
   201  	offset := len(h) - len(text)/2 // pad on the left
   202  	if _, err := hex.Decode(h[offset:], text); err != nil {
   203  		fmt.Println(err)
   204  		return fmt.Errorf("invalid hex storage key/value %q", text)
   205  	}
   206  	return nil
   207  }
   208  
   209  func (h storageJSON) MarshalText() ([]byte, error) {
   210  	return hexutil.Bytes(h[:]).MarshalText()
   211  }
   212  
   213  // GenesisMismatchError is raised when trying to overwrite an existing
   214  // genesis block with an incompatible one.
   215  type GenesisMismatchError struct {
   216  	Stored, New common.Hash
   217  }
   218  
   219  func (e *GenesisMismatchError) Error() string {
   220  	return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New)
   221  }
   222  
   223  // SetupGenesisBlock writes or updates the genesis block in db.
   224  // The block that will be used is:
   225  //
   226  //                          genesis == nil       genesis != nil
   227  //                       +------------------------------------------
   228  //     db has no genesis |  main-net default  |  genesis
   229  //     db has genesis    |  from DB           |  genesis (if compatible)
   230  //
   231  // The stored chain configuration will be updated if it is compatible (i.e. does not
   232  // specify a fork block below the local head block). In case of a conflict, the
   233  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   234  //
   235  // The returned chain configuration is never nil.
   236  func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   237  	return SetupGenesisBlockWithOverride(db, genesis, nil, nil)
   238  }
   239  
   240  func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, overrideArrowGlacier, overrideTerminalTotalDifficulty *big.Int) (*params.ChainConfig, common.Hash, error) {
   241  	if genesis != nil && genesis.Config == nil {
   242  		return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
   243  	}
   244  	// Just commit the new block if there is no stored genesis block.
   245  	stored := rawdb.ReadCanonicalHash(db, 0)
   246  	if (stored == common.Hash{}) {
   247  		if genesis == nil {
   248  			log.Info("Writing default main-net genesis block")
   249  			genesis = DefaultGenesisBlock()
   250  		} else {
   251  			log.Info("Writing custom genesis block")
   252  		}
   253  		block, err := genesis.Commit(db)
   254  		if err != nil {
   255  			return genesis.Config, common.Hash{}, err
   256  		}
   257  		return genesis.Config, block.Hash(), nil
   258  	}
   259  	// We have the genesis block in database(perhaps in ancient database)
   260  	// but the corresponding state is missing.
   261  	header := rawdb.ReadHeader(db, stored, 0)
   262  	if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, nil), nil); err != nil {
   263  		if genesis == nil {
   264  			genesis = DefaultGenesisBlock()
   265  		}
   266  		// Ensure the stored genesis matches with the given one.
   267  		hash := genesis.ToBlock(nil).Hash()
   268  		if hash != stored {
   269  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   270  		}
   271  		block, err := genesis.Commit(db)
   272  		if err != nil {
   273  			return genesis.Config, hash, err
   274  		}
   275  		return genesis.Config, block.Hash(), nil
   276  	}
   277  	// Check whether the genesis block is already written.
   278  	if genesis != nil {
   279  		hash := genesis.ToBlock(nil).Hash()
   280  		if hash != stored {
   281  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   282  		}
   283  	}
   284  	// Get the existing chain configuration.
   285  	newcfg := genesis.configOrDefault(stored)
   286  	if overrideArrowGlacier != nil {
   287  		newcfg.ArrowGlacierBlock = overrideArrowGlacier
   288  	}
   289  	if overrideTerminalTotalDifficulty != nil {
   290  		newcfg.TerminalTotalDifficulty = overrideTerminalTotalDifficulty
   291  	}
   292  	if err := newcfg.CheckConfigForkOrder(); err != nil {
   293  		return newcfg, common.Hash{}, err
   294  	}
   295  
   296  	storedcfg := rawdb.ReadChainConfig(db, stored)
   297  	if storedcfg == nil {
   298  		log.Warn("Found genesis block without chain config")
   299  		rawdb.WriteChainConfig(db, stored, newcfg)
   300  		return newcfg, stored, nil
   301  	}
   302  	// Special case: if a private network is being used (no genesis and also no
   303  	// mainnet hash in the database), we must not apply the `configOrDefault`
   304  	// chain config as that would be AllProtocolChanges (applying any new fork
   305  	// on top of an existing private network genesis block). In that case, only
   306  	// apply the overrides.
   307  	if genesis == nil && stored != params.MainnetGenesisHash {
   308  		newcfg = storedcfg
   309  		if overrideArrowGlacier != nil {
   310  			newcfg.ArrowGlacierBlock = overrideArrowGlacier
   311  		}
   312  		if overrideTerminalTotalDifficulty != nil {
   313  			newcfg.TerminalTotalDifficulty = overrideTerminalTotalDifficulty
   314  		}
   315  	}
   316  	// Check config compatibility and write the config. Compatibility errors
   317  	// are returned to the caller unless we're already at block zero.
   318  	height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
   319  	if height == nil {
   320  		return newcfg, stored, fmt.Errorf("missing block number for head header hash")
   321  	}
   322  	compatErr := storedcfg.CheckCompatible(newcfg, *height)
   323  	if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
   324  		return newcfg, stored, compatErr
   325  	}
   326  
   327  	rawdb.WriteChainConfig(db, stored, newcfg)
   328  	return newcfg, stored, nil
   329  }
   330  
   331  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   332  	switch {
   333  	case g != nil:
   334  		return g.Config
   335  	case ghash == params.MainnetGenesisHash:
   336  		return params.MainnetChainConfig
   337  	case ghash == params.RopstenGenesisHash:
   338  		return params.RopstenChainConfig
   339  	case ghash == params.SepoliaGenesisHash:
   340  		return params.SepoliaChainConfig
   341  	case ghash == params.RinkebyGenesisHash:
   342  		return params.RinkebyChainConfig
   343  	case ghash == params.GoerliGenesisHash:
   344  		return params.GoerliChainConfig
   345  	case ghash == params.MumbaiGenesisHash:
   346  		return params.MumbaiChainConfig
   347  	case ghash == params.BorMainnetGenesisHash:
   348  		return params.BorMainnetChainConfig
   349  	case ghash == params.KilnGenesisHash:
   350  		return DefaultKilnGenesisBlock().Config
   351  	default:
   352  		return params.AllEthashProtocolChanges
   353  	}
   354  }
   355  
   356  // ToBlock creates the genesis block and writes state of a genesis specification
   357  // to the given database (or discards it if nil).
   358  func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
   359  	if db == nil {
   360  		db = rawdb.NewMemoryDatabase()
   361  	}
   362  	root, err := g.Alloc.flush(db)
   363  	if err != nil {
   364  		panic(err)
   365  	}
   366  	head := &types.Header{
   367  		Number:     new(big.Int).SetUint64(g.Number),
   368  		Nonce:      types.EncodeNonce(g.Nonce),
   369  		Time:       g.Timestamp,
   370  		ParentHash: g.ParentHash,
   371  		Extra:      g.ExtraData,
   372  		GasLimit:   g.GasLimit,
   373  		GasUsed:    g.GasUsed,
   374  		BaseFee:    g.BaseFee,
   375  		Difficulty: g.Difficulty,
   376  		MixDigest:  g.Mixhash,
   377  		Coinbase:   g.Coinbase,
   378  		Root:       root,
   379  	}
   380  	if g.GasLimit == 0 {
   381  		head.GasLimit = params.GenesisGasLimit
   382  	}
   383  	if g.Difficulty == nil && g.Mixhash == (common.Hash{}) {
   384  		head.Difficulty = params.GenesisDifficulty
   385  	}
   386  	if g.Config != nil && g.Config.IsLondon(common.Big0) {
   387  		if g.BaseFee != nil {
   388  			head.BaseFee = g.BaseFee
   389  		} else {
   390  			head.BaseFee = new(big.Int).SetUint64(params.InitialBaseFee)
   391  		}
   392  	}
   393  	return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil))
   394  }
   395  
   396  // Commit writes the block and state of a genesis specification to the database.
   397  // The block is committed as the canonical head block.
   398  func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
   399  	block := g.ToBlock(db)
   400  	if block.Number().Sign() != 0 {
   401  		return nil, errors.New("can't commit genesis block with number > 0")
   402  	}
   403  	config := g.Config
   404  	if config == nil {
   405  		config = params.AllEthashProtocolChanges
   406  	}
   407  	if err := config.CheckConfigForkOrder(); err != nil {
   408  		return nil, err
   409  	}
   410  	if config.Clique != nil && len(block.Extra()) == 0 {
   411  		return nil, errors.New("can't start clique chain without signers")
   412  	}
   413  	if err := g.Alloc.write(db, block.Hash()); err != nil {
   414  		return nil, err
   415  	}
   416  	rawdb.WriteTd(db, block.Hash(), block.NumberU64(), block.Difficulty())
   417  	rawdb.WriteBlock(db, block)
   418  	rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
   419  	rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
   420  	rawdb.WriteHeadBlockHash(db, block.Hash())
   421  	rawdb.WriteHeadFastBlockHash(db, block.Hash())
   422  	rawdb.WriteHeadHeaderHash(db, block.Hash())
   423  	rawdb.WriteChainConfig(db, block.Hash(), config)
   424  	return block, nil
   425  }
   426  
   427  // MustCommit writes the genesis block and state to db, panicking on error.
   428  // The block is committed as the canonical head block.
   429  func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
   430  	block, err := g.Commit(db)
   431  	if err != nil {
   432  		panic(err)
   433  	}
   434  	return block
   435  }
   436  
   437  // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
   438  func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
   439  	g := Genesis{
   440  		Alloc:   GenesisAlloc{addr: {Balance: balance}},
   441  		BaseFee: big.NewInt(params.InitialBaseFee),
   442  	}
   443  	return g.MustCommit(db)
   444  }
   445  
   446  // DefaultGenesisBlock returns the Ethereum main net genesis block.
   447  func DefaultGenesisBlock() *Genesis {
   448  	return &Genesis{
   449  		Config:     params.MainnetChainConfig,
   450  		Nonce:      66,
   451  		ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
   452  		GasLimit:   5000,
   453  		Difficulty: big.NewInt(17179869184),
   454  		Alloc:      decodePrealloc(mainnetAllocData),
   455  	}
   456  }
   457  
   458  // DefaultRopstenGenesisBlock returns the Ropsten network genesis block.
   459  func DefaultRopstenGenesisBlock() *Genesis {
   460  	return &Genesis{
   461  		Config:     params.RopstenChainConfig,
   462  		Nonce:      66,
   463  		ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
   464  		GasLimit:   16777216,
   465  		Difficulty: big.NewInt(1048576),
   466  		Alloc:      decodePrealloc(ropstenAllocData),
   467  	}
   468  }
   469  
   470  // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
   471  func DefaultRinkebyGenesisBlock() *Genesis {
   472  	return &Genesis{
   473  		Config:     params.RinkebyChainConfig,
   474  		Timestamp:  1492009146,
   475  		ExtraData:  hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   476  		GasLimit:   4700000,
   477  		Difficulty: big.NewInt(1),
   478  		Alloc:      decodePrealloc(rinkebyAllocData),
   479  	}
   480  }
   481  
   482  // DefaultGoerliGenesisBlock returns the Görli network genesis block.
   483  func DefaultGoerliGenesisBlock() *Genesis {
   484  	return &Genesis{
   485  		Config:     params.GoerliChainConfig,
   486  		Timestamp:  1548854791,
   487  		ExtraData:  hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   488  		GasLimit:   10485760,
   489  		Difficulty: big.NewInt(1),
   490  		Alloc:      decodePrealloc(goerliAllocData),
   491  	}
   492  }
   493  
   494  // DefaultMumbaiGenesisBlock returns the Mumbai network genesis block.
   495  func DefaultMumbaiGenesisBlock() *Genesis {
   496  	return &Genesis{
   497  		Config:     params.MumbaiChainConfig,
   498  		Nonce:      0,
   499  		Timestamp:  1558348305,
   500  		GasLimit:   10000000,
   501  		Difficulty: big.NewInt(1),
   502  		Mixhash:    common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"),
   503  		Coinbase:   common.HexToAddress("0x0000000000000000000000000000000000000000"),
   504  		Alloc:      readPrealloc("allocs/mumbai.json"),
   505  	}
   506  }
   507  
   508  //DefaultBorMainnet returns the Bor Mainnet network gensis block.
   509  func DefaultBorMainnetGenesisBlock() *Genesis {
   510  	return &Genesis{
   511  		Config:     params.BorMainnetChainConfig,
   512  		Nonce:      0,
   513  		Timestamp:  1590824836,
   514  		GasLimit:   10000000,
   515  		Difficulty: big.NewInt(1),
   516  		Mixhash:    common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"),
   517  		Coinbase:   common.HexToAddress("0x0000000000000000000000000000000000000000"),
   518  		Alloc:      readPrealloc("allocs/bor_mainnet.json"),
   519  	}
   520  }
   521  
   522  // DefaultSepoliaGenesisBlock returns the Sepolia network genesis block.
   523  func DefaultSepoliaGenesisBlock() *Genesis {
   524  	return &Genesis{
   525  		Config:     params.SepoliaChainConfig,
   526  		Nonce:      0,
   527  		ExtraData:  []byte("Sepolia, Athens, Attica, Greece!"),
   528  		GasLimit:   0x1c9c380,
   529  		Difficulty: big.NewInt(0x20000),
   530  		Timestamp:  1633267481,
   531  		Alloc:      decodePrealloc(sepoliaAllocData),
   532  	}
   533  }
   534  
   535  func DefaultKilnGenesisBlock() *Genesis {
   536  	g := new(Genesis)
   537  	reader := strings.NewReader(KilnAllocData)
   538  	if err := json.NewDecoder(reader).Decode(g); err != nil {
   539  		panic(err)
   540  	}
   541  	return g
   542  }
   543  
   544  // DeveloperGenesisBlock returns the 'geth --dev' genesis block.
   545  func DeveloperGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *Genesis {
   546  	// Override the default period to the user requested one
   547  	config := *params.AllCliqueProtocolChanges
   548  	config.Clique = &params.CliqueConfig{
   549  		Period: period,
   550  		Epoch:  config.Clique.Epoch,
   551  	}
   552  
   553  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   554  	return &Genesis{
   555  		Config:     &config,
   556  		ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...),
   557  		GasLimit:   gasLimit,
   558  		BaseFee:    big.NewInt(params.InitialBaseFee),
   559  		Difficulty: big.NewInt(1),
   560  		Alloc: map[common.Address]GenesisAccount{
   561  			common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   562  			common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   563  			common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   564  			common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   565  			common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   566  			common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   567  			common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   568  			common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   569  			common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b
   570  			faucet:                           {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
   571  		},
   572  	}
   573  }
   574  
   575  func decodePrealloc(data string) GenesisAlloc {
   576  	var p []struct{ Addr, Balance *big.Int }
   577  	if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
   578  		panic(err)
   579  	}
   580  	ga := make(GenesisAlloc, len(p))
   581  	for _, account := range p {
   582  		ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
   583  	}
   584  	return ga
   585  }
   586  
   587  func readPrealloc(filename string) GenesisAlloc {
   588  	f, err := allocs.Open(filename)
   589  	if err != nil {
   590  		panic(fmt.Sprintf("Could not open genesis preallocation for %s: %v", filename, err))
   591  	}
   592  	defer f.Close()
   593  	decoder := json.NewDecoder(f)
   594  	ga := make(GenesisAlloc)
   595  	err = decoder.Decode(&ga)
   596  	if err != nil {
   597  		panic(fmt.Sprintf("Could not parse genesis preallocation for %s: %v", filename, err))
   598  	}
   599  	return ga
   600  }