genesis.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. package core
  17. import (
  18. "compress/bzip2"
  19. "compress/gzip"
  20. "encoding/base64"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "math/big"
  26. "strings"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. // WriteGenesisBlock writes the genesis block to the database as block number 0
  35. func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block, error) {
  36. contents, err := ioutil.ReadAll(reader)
  37. if err != nil {
  38. return nil, err
  39. }
  40. var genesis struct {
  41. ChainConfig *params.ChainConfig `json:"config"`
  42. Nonce string
  43. Timestamp string
  44. ParentHash string
  45. ExtraData string
  46. GasLimit string
  47. Difficulty string
  48. Mixhash string
  49. Coinbase string
  50. Alloc map[string]struct {
  51. Code string
  52. Storage map[string]string
  53. Balance string
  54. Nonce string
  55. }
  56. }
  57. if err := json.Unmarshal(contents, &genesis); err != nil {
  58. return nil, err
  59. }
  60. // creating with empty hash always works
  61. statedb, _ := state.New(common.Hash{}, chainDb)
  62. for addr, account := range genesis.Alloc {
  63. address := common.HexToAddress(addr)
  64. statedb.AddBalance(address, common.String2Big(account.Balance))
  65. statedb.SetCode(address, common.FromHex(account.Code))
  66. statedb.SetNonce(address, common.String2Big(account.Nonce).Uint64())
  67. for key, value := range account.Storage {
  68. statedb.SetState(address, common.HexToHash(key), common.HexToHash(value))
  69. }
  70. }
  71. root, stateBatch := statedb.CommitBatch(false)
  72. difficulty := common.String2Big(genesis.Difficulty)
  73. block := types.NewBlock(&types.Header{
  74. Nonce: types.EncodeNonce(common.String2Big(genesis.Nonce).Uint64()),
  75. Time: common.String2Big(genesis.Timestamp),
  76. ParentHash: common.HexToHash(genesis.ParentHash),
  77. Extra: common.FromHex(genesis.ExtraData),
  78. GasLimit: common.String2Big(genesis.GasLimit),
  79. Difficulty: difficulty,
  80. MixDigest: common.HexToHash(genesis.Mixhash),
  81. Coinbase: common.HexToAddress(genesis.Coinbase),
  82. Root: root,
  83. }, nil, nil, nil)
  84. if block := GetBlock(chainDb, block.Hash(), block.NumberU64()); block != nil {
  85. log.Info(fmt.Sprint("Genesis block already in chain. Writing canonical number"))
  86. err := WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
  87. if err != nil {
  88. return nil, err
  89. }
  90. return block, nil
  91. }
  92. if err := stateBatch.Write(); err != nil {
  93. return nil, fmt.Errorf("cannot write state: %v", err)
  94. }
  95. if err := WriteTd(chainDb, block.Hash(), block.NumberU64(), difficulty); err != nil {
  96. return nil, err
  97. }
  98. if err := WriteBlock(chainDb, block); err != nil {
  99. return nil, err
  100. }
  101. if err := WriteBlockReceipts(chainDb, block.Hash(), block.NumberU64(), nil); err != nil {
  102. return nil, err
  103. }
  104. if err := WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64()); err != nil {
  105. return nil, err
  106. }
  107. if err := WriteHeadBlockHash(chainDb, block.Hash()); err != nil {
  108. return nil, err
  109. }
  110. if err := WriteChainConfig(chainDb, block.Hash(), genesis.ChainConfig); err != nil {
  111. return nil, err
  112. }
  113. return block, nil
  114. }
  115. // GenesisBlockForTesting creates a block in which addr has the given wei balance.
  116. // The state trie of the block is written to db. the passed db needs to contain a state root
  117. func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
  118. statedb, _ := state.New(common.Hash{}, db)
  119. obj := statedb.GetOrNewStateObject(addr)
  120. obj.SetBalance(balance)
  121. root, err := statedb.Commit(false)
  122. if err != nil {
  123. panic(fmt.Sprintf("cannot write state: %v", err))
  124. }
  125. block := types.NewBlock(&types.Header{
  126. Difficulty: params.GenesisDifficulty,
  127. GasLimit: params.GenesisGasLimit,
  128. Root: root,
  129. }, nil, nil, nil)
  130. return block
  131. }
  132. type GenesisAccount struct {
  133. Address common.Address
  134. Balance *big.Int
  135. }
  136. func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount) *types.Block {
  137. accountJson := "{"
  138. for i, account := range accounts {
  139. if i != 0 {
  140. accountJson += ","
  141. }
  142. accountJson += fmt.Sprintf(`"0x%x":{"balance":"0x%x"}`, account.Address, account.Balance.Bytes())
  143. }
  144. accountJson += "}"
  145. testGenesis := fmt.Sprintf(`{
  146. "nonce":"0x%x",
  147. "gasLimit":"0x%x",
  148. "difficulty":"0x%x",
  149. "alloc": %s
  150. }`, types.EncodeNonce(0), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes(), accountJson)
  151. block, _ := WriteGenesisBlock(db, strings.NewReader(testGenesis))
  152. return block
  153. }
  154. // WriteDefaultGenesisBlock assembles the official Ethereum genesis block and
  155. // writes it - along with all associated state - into a chain database.
  156. func WriteDefaultGenesisBlock(chainDb ethdb.Database) (*types.Block, error) {
  157. return WriteGenesisBlock(chainDb, strings.NewReader(DefaultGenesisBlock()))
  158. }
  159. // WriteTestNetGenesisBlock assembles the test network genesis block and
  160. // writes it - along with all associated state - into a chain database.
  161. func WriteTestNetGenesisBlock(chainDb ethdb.Database) (*types.Block, error) {
  162. return WriteGenesisBlock(chainDb, strings.NewReader(DefaultTestnetGenesisBlock()))
  163. }
  164. // DefaultGenesisBlock assembles a JSON string representing the default Ethereum
  165. // genesis block.
  166. func DefaultGenesisBlock() string {
  167. reader, err := gzip.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultGenesisBlock)))
  168. if err != nil {
  169. panic(fmt.Sprintf("failed to access default genesis: %v", err))
  170. }
  171. blob, err := ioutil.ReadAll(reader)
  172. if err != nil {
  173. panic(fmt.Sprintf("failed to load default genesis: %v", err))
  174. }
  175. return string(blob)
  176. }
  177. // DefaultTestnetGenesisBlock assembles a JSON string representing the default Ethereum
  178. // test network genesis block.
  179. func DefaultTestnetGenesisBlock() string {
  180. reader := bzip2.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultTestnetGenesisBlock)))
  181. blob, err := ioutil.ReadAll(reader)
  182. if err != nil {
  183. panic(fmt.Sprintf("failed to load default genesis: %v", err))
  184. }
  185. return string(blob)
  186. }
  187. // DevGenesisBlock assembles a JSON string representing a local dev genesis block.
  188. func DevGenesisBlock() string {
  189. reader := bzip2.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultDevnetGenesisBlock)))
  190. blob, err := ioutil.ReadAll(reader)
  191. if err != nil {
  192. panic(fmt.Sprintf("failed to load dev genesis: %v", err))
  193. }
  194. return string(blob)
  195. }