genesis.go 8.4 KB

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