gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/core/genesis.go (about)

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