genesis.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. "errors"
  19. "fmt"
  20. "math/big"
  21. "strings"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/common/math"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/params"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. )
  32. //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
  33. //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
  34. var errGenesisNoConfig = errors.New("genesis has no chain configuration")
  35. // Genesis specifies the header fields, state of a genesis block. It also defines hard
  36. // fork switch-over blocks through the chain configuration.
  37. type Genesis struct {
  38. Config *params.ChainConfig `json:"config"`
  39. Nonce uint64 `json:"nonce"`
  40. Timestamp uint64 `json:"timestamp"`
  41. ParentHash common.Hash `json:"parentHash"`
  42. ExtraData []byte `json:"extraData"`
  43. GasLimit uint64 `json:"gasLimit" gencodec:"required"`
  44. Difficulty *big.Int `json:"difficulty" gencodec:"required"`
  45. Mixhash common.Hash `json:"mixHash"`
  46. Coinbase common.Address `json:"coinbase"`
  47. Alloc GenesisAlloc `json:"alloc" gencodec:"required"`
  48. }
  49. // GenesisAlloc specifies the initial state that is part of the genesis block.
  50. type GenesisAlloc map[common.Address]GenesisAccount
  51. // GenesisAccount is an account in the state of the genesis block.
  52. type GenesisAccount struct {
  53. Code []byte `json:"code,omitempty"`
  54. Storage map[common.Hash]common.Hash `json:"storage,omitempty"`
  55. Balance *big.Int `json:"balance" gencodec:"required"`
  56. Nonce uint64 `json:"nonce,omitempty"`
  57. }
  58. // field type overrides for gencodec
  59. type genesisSpecMarshaling struct {
  60. Nonce math.HexOrDecimal64
  61. Timestamp math.HexOrDecimal64
  62. ExtraData hexutil.Bytes
  63. GasLimit math.HexOrDecimal64
  64. Difficulty *math.HexOrDecimal256
  65. Alloc map[common.UnprefixedAddress]GenesisAccount
  66. }
  67. type genesisAccountMarshaling struct {
  68. Code hexutil.Bytes
  69. Balance *math.HexOrDecimal256
  70. Nonce math.HexOrDecimal64
  71. }
  72. // GenesisMismatchError is raised when trying to overwrite an existing
  73. // genesis block with an incompatible one.
  74. type GenesisMismatchError struct {
  75. Stored, New common.Hash
  76. }
  77. func (e *GenesisMismatchError) Error() string {
  78. return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8])
  79. }
  80. // SetupGenesisBlock writes or updates the genesis block in db.
  81. // The block that will be used is:
  82. //
  83. // genesis == nil genesis != nil
  84. // +------------------------------------------
  85. // db has no genesis | main-net default | genesis
  86. // db has genesis | from DB | genesis (if compatible)
  87. //
  88. // The stored chain configuration will be updated if it is compatible (i.e. does not
  89. // specify a fork block below the local head block). In case of a conflict, the
  90. // error is a *params.ConfigCompatError and the new, unwritten config is returned.
  91. //
  92. // The returned chain configuration is never nil.
  93. func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
  94. if genesis != nil && genesis.Config == nil {
  95. return params.AllProtocolChanges, common.Hash{}, errGenesisNoConfig
  96. }
  97. // Just commit the new block if there is no stored genesis block.
  98. stored := GetCanonicalHash(db, 0)
  99. if (stored == common.Hash{}) {
  100. if genesis == nil {
  101. log.Info("Writing default main-net genesis block")
  102. genesis = DefaultGenesisBlock()
  103. } else {
  104. log.Info("Writing custom genesis block")
  105. }
  106. block, err := genesis.Commit(db)
  107. return genesis.Config, block.Hash(), err
  108. }
  109. // Check whether the genesis block is already written.
  110. if genesis != nil {
  111. block, _ := genesis.ToBlock()
  112. hash := block.Hash()
  113. if hash != stored {
  114. return genesis.Config, block.Hash(), &GenesisMismatchError{stored, hash}
  115. }
  116. }
  117. // Get the existing chain configuration.
  118. newcfg := genesis.configOrDefault(stored)
  119. storedcfg, err := GetChainConfig(db, stored)
  120. if err != nil {
  121. if err == ErrChainConfigNotFound {
  122. // This case happens if a genesis write was interrupted.
  123. log.Warn("Found genesis block without chain config")
  124. err = WriteChainConfig(db, stored, newcfg)
  125. }
  126. return newcfg, stored, err
  127. }
  128. // Special case: don't change the existing config of a non-mainnet chain if no new
  129. // config is supplied. These chains would get AllProtocolChanges (and a compat error)
  130. // if we just continued here.
  131. if genesis == nil && stored != params.MainNetGenesisHash {
  132. return storedcfg, stored, nil
  133. }
  134. // Check config compatibility and write the config. Compatibility errors
  135. // are returned to the caller unless we're already at block zero.
  136. height := GetBlockNumber(db, GetHeadHeaderHash(db))
  137. if height == missingNumber {
  138. return newcfg, stored, fmt.Errorf("missing block number for head header hash")
  139. }
  140. compatErr := storedcfg.CheckCompatible(newcfg, height)
  141. if compatErr != nil && height != 0 && compatErr.RewindTo != 0 {
  142. return newcfg, stored, compatErr
  143. }
  144. return newcfg, stored, WriteChainConfig(db, stored, newcfg)
  145. }
  146. func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
  147. switch {
  148. case g != nil:
  149. return g.Config
  150. case ghash == params.MainNetGenesisHash:
  151. return params.MainnetChainConfig
  152. case ghash == params.TestNetGenesisHash:
  153. return params.TestnetChainConfig
  154. default:
  155. return params.AllProtocolChanges
  156. }
  157. }
  158. // ToBlock creates the block and state of a genesis specification.
  159. func (g *Genesis) ToBlock() (*types.Block, *state.StateDB) {
  160. db, _ := ethdb.NewMemDatabase()
  161. statedb, _ := state.New(common.Hash{}, db)
  162. for addr, account := range g.Alloc {
  163. statedb.AddBalance(addr, account.Balance)
  164. statedb.SetCode(addr, account.Code)
  165. statedb.SetNonce(addr, account.Nonce)
  166. for key, value := range account.Storage {
  167. statedb.SetState(addr, key, value)
  168. }
  169. }
  170. root := statedb.IntermediateRoot(false)
  171. head := &types.Header{
  172. Nonce: types.EncodeNonce(g.Nonce),
  173. Time: new(big.Int).SetUint64(g.Timestamp),
  174. ParentHash: g.ParentHash,
  175. Extra: g.ExtraData,
  176. GasLimit: new(big.Int).SetUint64(g.GasLimit),
  177. Difficulty: g.Difficulty,
  178. MixDigest: g.Mixhash,
  179. Coinbase: g.Coinbase,
  180. Root: root,
  181. }
  182. if g.GasLimit == 0 {
  183. head.GasLimit = params.GenesisGasLimit
  184. }
  185. if g.Difficulty == nil {
  186. head.Difficulty = params.GenesisDifficulty
  187. }
  188. return types.NewBlock(head, nil, nil, nil), statedb
  189. }
  190. // Commit writes the block and state of a genesis specification to the database.
  191. // The block is committed as the canonical head block.
  192. func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
  193. block, statedb := g.ToBlock()
  194. if _, err := statedb.CommitTo(db, false); err != nil {
  195. return nil, fmt.Errorf("cannot write state: %v", err)
  196. }
  197. if err := WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty); err != nil {
  198. return nil, err
  199. }
  200. if err := WriteBlock(db, block); err != nil {
  201. return nil, err
  202. }
  203. if err := WriteBlockReceipts(db, block.Hash(), block.NumberU64(), nil); err != nil {
  204. return nil, err
  205. }
  206. if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil {
  207. return nil, err
  208. }
  209. if err := WriteHeadBlockHash(db, block.Hash()); err != nil {
  210. return nil, err
  211. }
  212. if err := WriteHeadHeaderHash(db, block.Hash()); err != nil {
  213. return nil, err
  214. }
  215. config := g.Config
  216. if config == nil {
  217. config = params.AllProtocolChanges
  218. }
  219. return block, WriteChainConfig(db, block.Hash(), config)
  220. }
  221. // MustCommit writes the genesis block and state to db, panicking on error.
  222. // The block is committed as the canonical head block.
  223. func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
  224. block, err := g.Commit(db)
  225. if err != nil {
  226. panic(err)
  227. }
  228. return block
  229. }
  230. // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
  231. func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
  232. g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
  233. return g.MustCommit(db)
  234. }
  235. // DefaultGenesisBlock returns the Ethereum main net genesis block.
  236. func DefaultGenesisBlock() *Genesis {
  237. return &Genesis{
  238. Config: params.MainnetChainConfig,
  239. Nonce: 66,
  240. ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
  241. GasLimit: 5000,
  242. Difficulty: big.NewInt(17179869184),
  243. Alloc: decodePrealloc(mainnetAllocData),
  244. }
  245. }
  246. // DefaultTestnetGenesisBlock returns the Ropsten network genesis block.
  247. func DefaultTestnetGenesisBlock() *Genesis {
  248. return &Genesis{
  249. Config: params.TestnetChainConfig,
  250. Nonce: 66,
  251. ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
  252. GasLimit: 16777216,
  253. Difficulty: big.NewInt(1048576),
  254. Alloc: decodePrealloc(testnetAllocData),
  255. }
  256. }
  257. // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
  258. func DefaultRinkebyGenesisBlock() *Genesis {
  259. return &Genesis{
  260. Config: params.RinkebyChainConfig,
  261. Timestamp: 1492009146,
  262. ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
  263. GasLimit: 4700000,
  264. Difficulty: big.NewInt(1),
  265. Alloc: decodePrealloc(rinkebyAllocData),
  266. }
  267. }
  268. // DevGenesisBlock returns the 'geth --dev' genesis block.
  269. func DevGenesisBlock() *Genesis {
  270. return &Genesis{
  271. Config: params.AllProtocolChanges,
  272. Nonce: 42,
  273. GasLimit: 4712388,
  274. Difficulty: big.NewInt(131072),
  275. Alloc: decodePrealloc(devAllocData),
  276. }
  277. }
  278. func decodePrealloc(data string) GenesisAlloc {
  279. var p []struct{ Addr, Balance *big.Int }
  280. if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
  281. panic(err)
  282. }
  283. ga := make(GenesisAlloc, len(p))
  284. for _, account := range p {
  285. ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
  286. }
  287. return ga
  288. }