genesis.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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/common/math"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/log"
  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. balance, ok := math.ParseBig256(account.Balance)
  65. if !ok {
  66. return nil, fmt.Errorf("invalid balance for account %s: %q", addr, account.Balance)
  67. }
  68. nonce, ok := math.ParseUint64(account.Nonce)
  69. if !ok {
  70. return nil, fmt.Errorf("invalid nonce for account %s: %q", addr, account.Nonce)
  71. }
  72. address := common.HexToAddress(addr)
  73. statedb.AddBalance(address, balance)
  74. statedb.SetCode(address, common.FromHex(account.Code))
  75. statedb.SetNonce(address, nonce)
  76. for key, value := range account.Storage {
  77. statedb.SetState(address, common.HexToHash(key), common.HexToHash(value))
  78. }
  79. }
  80. root, stateBatch := statedb.CommitBatch(false)
  81. difficulty, ok := math.ParseBig256(genesis.Difficulty)
  82. if !ok {
  83. return nil, fmt.Errorf("invalid difficulty: %q", genesis.Difficulty)
  84. }
  85. gaslimit, ok := math.ParseUint64(genesis.GasLimit)
  86. if !ok {
  87. return nil, fmt.Errorf("invalid gas limit: %q", genesis.GasLimit)
  88. }
  89. nonce, ok := math.ParseUint64(genesis.Nonce)
  90. if !ok {
  91. return nil, fmt.Errorf("invalid nonce: %q", genesis.Nonce)
  92. }
  93. timestamp, ok := math.ParseBig256(genesis.Timestamp)
  94. if !ok {
  95. return nil, fmt.Errorf("invalid timestamp: %q", genesis.Timestamp)
  96. }
  97. block := types.NewBlock(&types.Header{
  98. Nonce: types.EncodeNonce(nonce),
  99. Time: timestamp,
  100. ParentHash: common.HexToHash(genesis.ParentHash),
  101. Extra: common.FromHex(genesis.ExtraData),
  102. GasLimit: new(big.Int).SetUint64(gaslimit),
  103. Difficulty: difficulty,
  104. MixDigest: common.HexToHash(genesis.Mixhash),
  105. Coinbase: common.HexToAddress(genesis.Coinbase),
  106. Root: root,
  107. }, nil, nil, nil)
  108. if block := GetBlock(chainDb, block.Hash(), block.NumberU64()); block != nil {
  109. log.Info(fmt.Sprint("Genesis block already in chain. Writing canonical number"))
  110. err := WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64())
  111. if err != nil {
  112. return nil, err
  113. }
  114. return block, nil
  115. }
  116. if err := stateBatch.Write(); err != nil {
  117. return nil, fmt.Errorf("cannot write state: %v", err)
  118. }
  119. if err := WriteTd(chainDb, block.Hash(), block.NumberU64(), difficulty); err != nil {
  120. return nil, err
  121. }
  122. if err := WriteBlock(chainDb, block); err != nil {
  123. return nil, err
  124. }
  125. if err := WriteBlockReceipts(chainDb, block.Hash(), block.NumberU64(), nil); err != nil {
  126. return nil, err
  127. }
  128. if err := WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64()); err != nil {
  129. return nil, err
  130. }
  131. if err := WriteHeadBlockHash(chainDb, block.Hash()); err != nil {
  132. return nil, err
  133. }
  134. if err := WriteChainConfig(chainDb, block.Hash(), genesis.ChainConfig); err != nil {
  135. return nil, err
  136. }
  137. return block, nil
  138. }
  139. // GenesisBlockForTesting creates a block in which addr has the given wei balance.
  140. // The state trie of the block is written to db. the passed db needs to contain a state root
  141. func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
  142. statedb, _ := state.New(common.Hash{}, db)
  143. obj := statedb.GetOrNewStateObject(addr)
  144. obj.SetBalance(balance)
  145. root, err := statedb.Commit(false)
  146. if err != nil {
  147. panic(fmt.Sprintf("cannot write state: %v", err))
  148. }
  149. block := types.NewBlock(&types.Header{
  150. Difficulty: params.GenesisDifficulty,
  151. GasLimit: params.GenesisGasLimit,
  152. Root: root,
  153. }, nil, nil, nil)
  154. return block
  155. }
  156. type GenesisAccount struct {
  157. Address common.Address
  158. Balance *big.Int
  159. }
  160. func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount) *types.Block {
  161. accountJson := "{"
  162. for i, account := range accounts {
  163. if i != 0 {
  164. accountJson += ","
  165. }
  166. accountJson += fmt.Sprintf(`"0x%x":{"balance":"%d"}`, account.Address, account.Balance)
  167. }
  168. accountJson += "}"
  169. testGenesis := fmt.Sprintf(`{
  170. "nonce":"0x%x",
  171. "gasLimit":"0x%x",
  172. "difficulty":"0x%x",
  173. "alloc": %s
  174. }`, types.EncodeNonce(0), params.GenesisGasLimit.Bytes(), params.GenesisDifficulty.Bytes(), accountJson)
  175. block, err := WriteGenesisBlock(db, strings.NewReader(testGenesis))
  176. if err != nil {
  177. panic(err)
  178. }
  179. return block
  180. }
  181. // WriteDefaultGenesisBlock assembles the official Ethereum genesis block and
  182. // writes it - along with all associated state - into a chain database.
  183. func WriteDefaultGenesisBlock(chainDb ethdb.Database) (*types.Block, error) {
  184. return WriteGenesisBlock(chainDb, strings.NewReader(DefaultGenesisBlock()))
  185. }
  186. // WriteTestNetGenesisBlock assembles the test network genesis block and
  187. // writes it - along with all associated state - into a chain database.
  188. func WriteTestNetGenesisBlock(chainDb ethdb.Database) (*types.Block, error) {
  189. return WriteGenesisBlock(chainDb, strings.NewReader(DefaultTestnetGenesisBlock()))
  190. }
  191. // DefaultGenesisBlock assembles a JSON string representing the default Ethereum
  192. // genesis block.
  193. func DefaultGenesisBlock() string {
  194. reader, err := gzip.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultGenesisBlock)))
  195. if err != nil {
  196. panic(fmt.Sprintf("failed to access default genesis: %v", err))
  197. }
  198. blob, err := ioutil.ReadAll(reader)
  199. if err != nil {
  200. panic(fmt.Sprintf("failed to load default genesis: %v", err))
  201. }
  202. return string(blob)
  203. }
  204. // DefaultTestnetGenesisBlock assembles a JSON string representing the default Ethereum
  205. // test network genesis block.
  206. func DefaultTestnetGenesisBlock() string {
  207. reader := bzip2.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultTestnetGenesisBlock)))
  208. blob, err := ioutil.ReadAll(reader)
  209. if err != nil {
  210. panic(fmt.Sprintf("failed to load default genesis: %v", err))
  211. }
  212. return string(blob)
  213. }
  214. // DevGenesisBlock assembles a JSON string representing a local dev genesis block.
  215. func DevGenesisBlock() string {
  216. reader := bzip2.NewReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(defaultDevnetGenesisBlock)))
  217. blob, err := ioutil.ReadAll(reader)
  218. if err != nil {
  219. panic(fmt.Sprintf("failed to load dev genesis: %v", err))
  220. }
  221. return string(blob)
  222. }