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