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