genesis.go 7.1 KB

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