github.com/vccomnet/occchain@v0.0.0-20181129092339-c57d4bab23fb/core/genesis.go (about)

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