github.com/beyonderyue/gochain@v2.2.26+incompatible/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  	"time"
    27  
    28  	"github.com/gochain-io/gochain/common"
    29  	"github.com/gochain-io/gochain/common/hexutil"
    30  	"github.com/gochain-io/gochain/common/math"
    31  	"github.com/gochain-io/gochain/core/rawdb"
    32  	"github.com/gochain-io/gochain/core/state"
    33  	"github.com/gochain-io/gochain/core/types"
    34  	"github.com/gochain-io/gochain/ethdb"
    35  	"github.com/gochain-io/gochain/log"
    36  	"github.com/gochain-io/gochain/params"
    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  	Signers    []common.Address    `json:"signers"`
    52  	Voters     []common.Address    `json:"voters"`
    53  	Signer     []byte              `json:"signer"`
    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  }
    66  
    67  // GenesisAlloc specifies the initial state that is part of the genesis block.
    68  type GenesisAlloc map[common.Address]GenesisAccount
    69  
    70  func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
    71  	m := make(map[common.UnprefixedAddress]GenesisAccount)
    72  	if err := json.Unmarshal(data, &m); err != nil {
    73  		return err
    74  	}
    75  	*ga = make(GenesisAlloc)
    76  	for addr, a := range m {
    77  		(*ga)[common.Address(addr)] = a
    78  	}
    79  	return nil
    80  }
    81  
    82  func (ga *GenesisAlloc) Total() *big.Int {
    83  	sum := new(big.Int)
    84  	if ga == nil {
    85  		return sum
    86  	}
    87  	for _, st := range *ga {
    88  		sum = sum.Add(sum, st.Balance)
    89  	}
    90  	return sum
    91  }
    92  
    93  // GenesisAccount is an account in the state of the genesis block.
    94  type GenesisAccount struct {
    95  	Code       []byte                      `json:"code,omitempty"`
    96  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
    97  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
    98  	Nonce      uint64                      `json:"nonce,omitempty"`
    99  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
   100  }
   101  
   102  // field type overrides for gencodec
   103  type genesisSpecMarshaling struct {
   104  	Nonce      math.HexOrDecimal64
   105  	Timestamp  math.HexOrDecimal64
   106  	ExtraData  hexutil.Bytes
   107  	Signer     hexutil.Bytes
   108  	GasLimit   math.HexOrDecimal64
   109  	GasUsed    math.HexOrDecimal64
   110  	Number     math.HexOrDecimal64
   111  	Difficulty *math.HexOrDecimal256
   112  	Alloc      map[common.UnprefixedAddress]GenesisAccount
   113  }
   114  
   115  type genesisAccountMarshaling struct {
   116  	Code       hexutil.Bytes
   117  	Balance    *math.HexOrDecimal256
   118  	Nonce      math.HexOrDecimal64
   119  	Storage    map[storageJSON]storageJSON
   120  	PrivateKey hexutil.Bytes
   121  }
   122  
   123  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   124  // unmarshaling from hex.
   125  type storageJSON common.Hash
   126  
   127  func (h *storageJSON) UnmarshalText(text []byte) error {
   128  	text = bytes.TrimPrefix(text, []byte("0x"))
   129  	if len(text) > 64 {
   130  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   131  	}
   132  	offset := len(h) - len(text)/2 // pad on the left
   133  	if _, err := hex.Decode(h[offset:], text); err != nil {
   134  		fmt.Println(err)
   135  		return fmt.Errorf("invalid hex storage key/value %q", text)
   136  	}
   137  	return nil
   138  }
   139  
   140  func (h storageJSON) MarshalText() ([]byte, error) {
   141  	return hexutil.Bytes(h[:]).MarshalText()
   142  }
   143  
   144  // GenesisMismatchError is raised when trying to overwrite an existing
   145  // genesis block with an incompatible one.
   146  type GenesisMismatchError struct {
   147  	Stored, New common.Hash
   148  }
   149  
   150  func (e *GenesisMismatchError) Error() string {
   151  	return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8])
   152  }
   153  
   154  // SetupGenesisBlock writes or updates the genesis block in db.
   155  // The block that will be used is:
   156  //
   157  //                          genesis == nil       genesis != nil
   158  //                       +------------------------------------------
   159  //     db has no genesis |  main-net default  |  genesis
   160  //     db has genesis    |  from DB           |  genesis (if compatible)
   161  //
   162  // The stored chain configuration will be updated if it is compatible (i.e. does not
   163  // specify a fork block below the local head block). In case of a conflict, the
   164  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   165  //
   166  // The returned chain configuration is never nil.
   167  func SetupGenesisBlock(db common.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   168  	if genesis != nil && genesis.Config == nil {
   169  		return params.AllCliqueProtocolChanges, common.Hash{}, errGenesisNoConfig
   170  	}
   171  
   172  	// Just commit the new block if there is no stored genesis block.
   173  	stored := rawdb.ReadCanonicalHash(db, 0)
   174  	if (stored == common.Hash{}) {
   175  		if genesis == nil {
   176  			log.Info("Writing default main-net genesis block")
   177  			genesis = DefaultGenesisBlock()
   178  		} else {
   179  			log.Info("Writing custom genesis block")
   180  		}
   181  		block, err := genesis.Commit(db)
   182  		return genesis.Config, block.Hash(), err
   183  	}
   184  
   185  	// Check whether the genesis block is already written.
   186  	if genesis != nil {
   187  		hash := genesis.ToBlock(nil).Hash()
   188  		if hash != stored {
   189  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   190  		}
   191  	}
   192  
   193  	// Get the existing chain configuration.
   194  	newcfg := genesis.configOrDefault(stored)
   195  	storedcfg := rawdb.ReadChainConfig(db.GlobalTable(), stored)
   196  	if storedcfg == nil {
   197  		// This case happens if a genesis write was interrupted.
   198  		log.Warn("Found genesis block without chain config")
   199  		rawdb.WriteChainConfig(db.GlobalTable(), stored, newcfg)
   200  		return newcfg, stored, nil
   201  	}
   202  	// Special case: don't change the existing config of a non-mainnet chain if no new
   203  	// config is supplied. These chains would get AllProtocolChanges (and a compat error)
   204  	// if we just continued here.
   205  	if genesis == nil && stored != params.MainnetGenesisHash {
   206  		return storedcfg, stored, nil
   207  	}
   208  
   209  	// Check config compatibility and write the config. Compatibility errors
   210  	// are returned to the caller unless we're already at block zero.
   211  	height := rawdb.ReadHeaderNumber(db.GlobalTable(), rawdb.ReadHeadHeaderHash(db.GlobalTable()))
   212  	if height == nil {
   213  		return newcfg, stored, fmt.Errorf("missing block number for head header hash")
   214  	}
   215  	compatErr := storedcfg.CheckCompatible(newcfg, *height)
   216  	if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
   217  		return newcfg, stored, compatErr
   218  	}
   219  	rawdb.WriteChainConfig(db.GlobalTable(), stored, newcfg)
   220  	return newcfg, stored, nil
   221  }
   222  
   223  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   224  	switch {
   225  	case g != nil:
   226  		return g.Config
   227  	case ghash == params.MainnetGenesisHash:
   228  		return params.MainnetChainConfig
   229  	case ghash == params.TestnetGenesisHash:
   230  		return params.TestnetChainConfig
   231  	default:
   232  		return params.AllCliqueProtocolChanges
   233  	}
   234  }
   235  
   236  // ToBlock creates the genesis block and writes state of a genesis specification
   237  // to the given database (or discards it if nil).
   238  func (g *Genesis) ToBlock(db common.Database) *types.Block {
   239  	if db == nil {
   240  		db = ethdb.NewMemDatabase()
   241  	}
   242  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
   243  	for addr, account := range g.Alloc {
   244  		statedb.AddBalance(addr, account.Balance)
   245  		statedb.SetCode(addr, account.Code)
   246  		statedb.SetNonce(addr, account.Nonce)
   247  		for key, value := range account.Storage {
   248  			statedb.SetState(addr, key, value)
   249  		}
   250  	}
   251  	root := statedb.IntermediateRoot(false)
   252  	head := &types.Header{
   253  		Number:     new(big.Int).SetUint64(g.Number),
   254  		Nonce:      types.EncodeNonce(g.Nonce),
   255  		Time:       new(big.Int).SetUint64(g.Timestamp),
   256  		ParentHash: g.ParentHash,
   257  		Extra:      g.ExtraData,
   258  		Signers:    g.Signers,
   259  		Voters:     g.Voters,
   260  		Signer:     g.Signer,
   261  		GasLimit:   g.GasLimit,
   262  		GasUsed:    g.GasUsed,
   263  		Difficulty: g.Difficulty,
   264  		MixDigest:  g.Mixhash,
   265  		Coinbase:   g.Coinbase,
   266  		Root:       root,
   267  	}
   268  	if g.GasLimit == 0 {
   269  		head.GasLimit = params.GenesisGasLimit
   270  	}
   271  	if g.Difficulty == nil {
   272  		head.Difficulty = big.NewInt(1)
   273  	}
   274  	if _, err := statedb.Commit(false); err != nil {
   275  		log.Error("Cannot commit genesis to state db", "err", err)
   276  	}
   277  	if err := statedb.Database().TrieDB().Commit(root, true); err != nil {
   278  		log.Error("Cannot commit genesis to trie db", "err", err)
   279  	}
   280  
   281  	return types.NewBlock(head, nil, nil, nil)
   282  }
   283  
   284  // Commit writes the block and state of a genesis specification to the database.
   285  // The block is committed as the canonical head block.
   286  func (g *Genesis) Commit(db common.Database) (*types.Block, error) {
   287  	block := g.ToBlock(db)
   288  	if block.Number().Sign() != 0 {
   289  		return nil, fmt.Errorf("can't commit genesis block with number > 0")
   290  	}
   291  	rawdb.WriteTd(db.GlobalTable(), block.Hash(), block.NumberU64(), g.Difficulty)
   292  	rawdb.WriteBlock(db, block)
   293  	rawdb.WriteReceipts(db.ReceiptTable(), block.Hash(), block.NumberU64(), nil)
   294  	rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
   295  	rawdb.WriteHeadBlockHash(db.GlobalTable(), block.Hash())
   296  	rawdb.WriteHeadHeaderHash(db.GlobalTable(), block.Hash())
   297  	config := g.Config
   298  	if config == nil {
   299  		config = params.AllCliqueProtocolChanges
   300  	}
   301  	rawdb.WriteChainConfig(db.GlobalTable(), block.Hash(), config)
   302  	return block, nil
   303  }
   304  
   305  // MustCommit writes the genesis block and state to db, panicking on error.
   306  // The block is committed as the canonical head block.
   307  func (g *Genesis) MustCommit(db common.Database) *types.Block {
   308  	block, err := g.Commit(db)
   309  	if err != nil {
   310  		panic(err)
   311  	}
   312  	return block
   313  }
   314  
   315  // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
   316  func GenesisBlockForTesting(db common.Database, addr common.Address, balance *big.Int) *types.Block {
   317  	g := Genesis{
   318  		Config: params.AllCliqueProtocolChanges,
   319  		Alloc:  GenesisAlloc{addr: {Balance: balance}},
   320  		Signer: hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   321  	}
   322  	return g.MustCommit(db)
   323  }
   324  
   325  // DefaultGenesisBlock returns the GoChain main net genesis block.
   326  func DefaultGenesisBlock() *Genesis {
   327  	allocAddr := common.HexToAddress("0xF75B6E2D2d69Da07f2940e239E25229350f8103f")
   328  	alloc, ok := new(big.Int).SetString("1000000000000000000000000000", 10)
   329  	if !ok {
   330  		panic("failed to parse big.Int string")
   331  	}
   332  	var extra = []byte("GoChain")
   333  	return &Genesis{
   334  		Config:     params.MainnetChainConfig,
   335  		Timestamp:  1526400000,
   336  		ExtraData:  append(extra, make([]byte, 32-len(extra))...),
   337  		GasLimit:   params.GenesisGasLimit,
   338  		Difficulty: big.NewInt(1),
   339  		Signers: []common.Address{
   340  			common.HexToAddress("0xed7f2e81b0264177e0df8f275f97fd74fa51a896"),
   341  			common.HexToAddress("0x3ad14430951aba12068a8167cebe3ddd57614432"),
   342  			common.HexToAddress("0x3729d2e93e8037f87a2c9afe34cb84b7069e4dea"),
   343  			common.HexToAddress("0xf6290b7f9f871d21317acc259f2ae23c0aa69c73"),
   344  			common.HexToAddress("0xf7678aa7f42bc017f3d6011ca27aed400647960d"),
   345  		},
   346  		Voters: []common.Address{
   347  			common.HexToAddress("0xed7f2e81b0264177e0df8f275f97fd74fa51a896"),
   348  		},
   349  		Signer: hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   350  		Alloc:  GenesisAlloc{allocAddr: {Balance: alloc}},
   351  	}
   352  }
   353  
   354  // DefaultTestnetGenesisBlock returns the GoChain Testnet network genesis block.
   355  func DefaultTestnetGenesisBlock() *Genesis {
   356  	alloc, ok := new(big.Int).SetString("1000000000000000000000000000", 10)
   357  	if !ok {
   358  		panic("failed to parse big.Int string")
   359  	}
   360  	return &Genesis{
   361  		Config:     params.TestnetChainConfig,
   362  		Timestamp:  1526048200,
   363  		ExtraData:  hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000"),
   364  		GasLimit:   params.GenesisGasLimit,
   365  		Difficulty: big.NewInt(1),
   366  		Signers: []common.Address{
   367  			common.HexToAddress("0x7aeceb5d345a01f8014a4320ab1f3d467c0c086a"),
   368  			common.HexToAddress("0xdd7e460302a911f9162a208370cdcdc37b892453"),
   369  			common.HexToAddress("0x10a8a552c8a8945f32f6fded5e44d9101b3491d8"),
   370  		},
   371  		Voters: []common.Address{
   372  			common.HexToAddress("0x7aeceb5d345a01f8014a4320ab1f3d467c0c086a"),
   373  		},
   374  		Signer: hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   375  		Alloc: GenesisAlloc{
   376  			common.HexToAddress("0x2Fe70F1Df222C85ad6Dd24a3376Eb5ac32136978"): {
   377  				Balance: alloc,
   378  			},
   379  		},
   380  	}
   381  }
   382  
   383  // DeveloperGenesisBlock returns the 'gochain --dev' genesis block. Note, this must
   384  // be seeded with the faucet address.
   385  func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
   386  	// Override the default period to the user requested one
   387  	config := *params.AllCliqueProtocolChanges
   388  	config.Clique.Period = period
   389  
   390  	alloc, ok := new(big.Int).SetString("1000000000000000000000000000", 10)
   391  	if !ok {
   392  		panic("failed to parse big.Int string")
   393  	}
   394  	var extra = []byte(faucet.Hex())[:32]
   395  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   396  	return &Genesis{
   397  		Config:     &config,
   398  		Timestamp:  uint64(time.Now().Unix()),
   399  		ExtraData:  append(extra, make([]byte, 32-len(extra))...),
   400  		GasLimit:   params.GenesisGasLimit,
   401  		Difficulty: big.NewInt(1),
   402  		Signers:    []common.Address{faucet},
   403  		Voters:     []common.Address{faucet},
   404  		Signer:     hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
   405  		Alloc:      GenesisAlloc{faucet: {Balance: alloc}},
   406  	}
   407  }