genesis.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. "bytes"
  19. "encoding/hex"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "strings"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/hexutil"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. )
  37. //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
  38. //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
  39. var errGenesisNoConfig = errors.New("genesis has no chain configuration")
  40. // Genesis specifies the header fields, state of a genesis block. It also defines hard
  41. // fork switch-over blocks through the chain configuration.
  42. type Genesis struct {
  43. Config *params.ChainConfig `json:"config"`
  44. Nonce uint64 `json:"nonce"`
  45. Timestamp uint64 `json:"timestamp"`
  46. ExtraData []byte `json:"extraData"`
  47. GasLimit uint64 `json:"gasLimit" gencodec:"required"`
  48. Difficulty *big.Int `json:"difficulty" gencodec:"required"`
  49. Mixhash common.Hash `json:"mixHash"`
  50. Coinbase common.Address `json:"coinbase"`
  51. Alloc GenesisAlloc `json:"alloc" gencodec:"required"`
  52. // These fields are used for consensus tests. Please don't use them
  53. // in actual genesis blocks.
  54. Number uint64 `json:"number"`
  55. GasUsed uint64 `json:"gasUsed"`
  56. ParentHash common.Hash `json:"parentHash"`
  57. }
  58. // GenesisAlloc specifies the initial state that is part of the genesis block.
  59. type GenesisAlloc map[common.Address]GenesisAccount
  60. func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
  61. m := make(map[common.UnprefixedAddress]GenesisAccount)
  62. if err := json.Unmarshal(data, &m); err != nil {
  63. return err
  64. }
  65. *ga = make(GenesisAlloc)
  66. for addr, a := range m {
  67. (*ga)[common.Address(addr)] = a
  68. }
  69. return nil
  70. }
  71. // GenesisAccount is an account in the state of the genesis block.
  72. type GenesisAccount struct {
  73. Code []byte `json:"code,omitempty"`
  74. Storage map[common.Hash]common.Hash `json:"storage,omitempty"`
  75. Balance *big.Int `json:"balance" gencodec:"required"`
  76. Nonce uint64 `json:"nonce,omitempty"`
  77. PrivateKey []byte `json:"secretKey,omitempty"` // for tests
  78. }
  79. // field type overrides for gencodec
  80. type genesisSpecMarshaling struct {
  81. Nonce math.HexOrDecimal64
  82. Timestamp math.HexOrDecimal64
  83. ExtraData hexutil.Bytes
  84. GasLimit math.HexOrDecimal64
  85. GasUsed math.HexOrDecimal64
  86. Number math.HexOrDecimal64
  87. Difficulty *math.HexOrDecimal256
  88. Alloc map[common.UnprefixedAddress]GenesisAccount
  89. }
  90. type genesisAccountMarshaling struct {
  91. Code hexutil.Bytes
  92. Balance *math.HexOrDecimal256
  93. Nonce math.HexOrDecimal64
  94. Storage map[storageJSON]storageJSON
  95. PrivateKey hexutil.Bytes
  96. }
  97. // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
  98. // unmarshaling from hex.
  99. type storageJSON common.Hash
  100. func (h *storageJSON) UnmarshalText(text []byte) error {
  101. text = bytes.TrimPrefix(text, []byte("0x"))
  102. if len(text) > 64 {
  103. return fmt.Errorf("too many hex characters in storage key/value %q", text)
  104. }
  105. offset := len(h) - len(text)/2 // pad on the left
  106. if _, err := hex.Decode(h[offset:], text); err != nil {
  107. fmt.Println(err)
  108. return fmt.Errorf("invalid hex storage key/value %q", text)
  109. }
  110. return nil
  111. }
  112. func (h storageJSON) MarshalText() ([]byte, error) {
  113. return hexutil.Bytes(h[:]).MarshalText()
  114. }
  115. // GenesisMismatchError is raised when trying to overwrite an existing
  116. // genesis block with an incompatible one.
  117. type GenesisMismatchError struct {
  118. Stored, New common.Hash
  119. }
  120. func (e *GenesisMismatchError) Error() string {
  121. return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New)
  122. }
  123. // SetupGenesisBlock writes or updates the genesis block in db.
  124. // The block that will be used is:
  125. //
  126. // genesis == nil genesis != nil
  127. // +------------------------------------------
  128. // db has no genesis | main-net default | genesis
  129. // db has genesis | from DB | genesis (if compatible)
  130. //
  131. // The stored chain configuration will be updated if it is compatible (i.e. does not
  132. // specify a fork block below the local head block). In case of a conflict, the
  133. // error is a *params.ConfigCompatError and the new, unwritten config is returned.
  134. //
  135. // The returned chain configuration is never nil.
  136. func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
  137. if genesis != nil && genesis.Config == nil {
  138. return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
  139. }
  140. // Just commit the new block if there is no stored genesis block.
  141. stored := rawdb.ReadCanonicalHash(db, 0)
  142. if (stored == common.Hash{}) {
  143. if genesis == nil {
  144. log.Info("Writing default main-net genesis block")
  145. genesis = DefaultGenesisBlock()
  146. } else {
  147. log.Info("Writing custom genesis block")
  148. }
  149. block, err := genesis.Commit(db)
  150. if err != nil {
  151. return genesis.Config, common.Hash{}, err
  152. }
  153. return genesis.Config, block.Hash(), nil
  154. }
  155. // We have the genesis block in database(perhaps in ancient database)
  156. // but the corresponding state is missing.
  157. header := rawdb.ReadHeader(db, stored, 0)
  158. if _, err := state.New(header.Root, state.NewDatabaseWithCache(db, 0, ""), nil); err != nil {
  159. if genesis == nil {
  160. genesis = DefaultGenesisBlock()
  161. }
  162. // Ensure the stored genesis matches with the given one.
  163. hash := genesis.ToBlock(nil).Hash()
  164. if hash != stored {
  165. return genesis.Config, hash, &GenesisMismatchError{stored, hash}
  166. }
  167. block, err := genesis.Commit(db)
  168. if err != nil {
  169. return genesis.Config, hash, err
  170. }
  171. return genesis.Config, block.Hash(), nil
  172. }
  173. // Check whether the genesis block is already written.
  174. if genesis != nil {
  175. hash := genesis.ToBlock(nil).Hash()
  176. if hash != stored {
  177. return genesis.Config, hash, &GenesisMismatchError{stored, hash}
  178. }
  179. }
  180. // Get the existing chain configuration.
  181. newcfg := genesis.configOrDefault(stored)
  182. if err := newcfg.CheckConfigForkOrder(); err != nil {
  183. return newcfg, common.Hash{}, err
  184. }
  185. storedcfg := rawdb.ReadChainConfig(db, stored)
  186. if storedcfg == nil {
  187. log.Warn("Found genesis block without chain config")
  188. rawdb.WriteChainConfig(db, stored, newcfg)
  189. return newcfg, stored, nil
  190. }
  191. // Special case: don't change the existing config of a non-mainnet chain if no new
  192. // config is supplied. These chains would get AllProtocolChanges (and a compat error)
  193. // if we just continued here.
  194. if genesis == nil && stored != params.MainnetGenesisHash {
  195. return storedcfg, stored, nil
  196. }
  197. // Check config compatibility and write the config. Compatibility errors
  198. // are returned to the caller unless we're already at block zero.
  199. height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
  200. if height == nil {
  201. return newcfg, stored, fmt.Errorf("missing block number for head header hash")
  202. }
  203. compatErr := storedcfg.CheckCompatible(newcfg, *height)
  204. if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
  205. return newcfg, stored, compatErr
  206. }
  207. rawdb.WriteChainConfig(db, stored, newcfg)
  208. return newcfg, stored, nil
  209. }
  210. func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
  211. switch {
  212. case g != nil:
  213. return g.Config
  214. case ghash == params.MainnetGenesisHash:
  215. return params.MainnetChainConfig
  216. case ghash == params.RopstenGenesisHash:
  217. return params.RopstenChainConfig
  218. case ghash == params.RinkebyGenesisHash:
  219. return params.RinkebyChainConfig
  220. case ghash == params.GoerliGenesisHash:
  221. return params.GoerliChainConfig
  222. case ghash == params.YoloV1GenesisHash:
  223. return params.YoloV1ChainConfig
  224. default:
  225. return params.AllEthashProtocolChanges
  226. }
  227. }
  228. // ToBlock creates the genesis block and writes state of a genesis specification
  229. // to the given database (or discards it if nil).
  230. func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
  231. if db == nil {
  232. db = rawdb.NewMemoryDatabase()
  233. }
  234. statedb, _ := state.New(common.Hash{}, state.NewDatabase(db), nil)
  235. for addr, account := range g.Alloc {
  236. statedb.AddBalance(addr, account.Balance)
  237. statedb.SetCode(addr, account.Code)
  238. statedb.SetNonce(addr, account.Nonce)
  239. for key, value := range account.Storage {
  240. statedb.SetState(addr, key, value)
  241. }
  242. }
  243. root := statedb.IntermediateRoot(false)
  244. head := &types.Header{
  245. Number: new(big.Int).SetUint64(g.Number),
  246. Nonce: types.EncodeNonce(g.Nonce),
  247. Time: g.Timestamp,
  248. ParentHash: g.ParentHash,
  249. Extra: g.ExtraData,
  250. GasLimit: g.GasLimit,
  251. GasUsed: g.GasUsed,
  252. Difficulty: g.Difficulty,
  253. MixDigest: g.Mixhash,
  254. Coinbase: g.Coinbase,
  255. Root: root,
  256. }
  257. if g.GasLimit == 0 {
  258. head.GasLimit = params.GenesisGasLimit
  259. }
  260. if g.Difficulty == nil {
  261. head.Difficulty = params.GenesisDifficulty
  262. }
  263. statedb.Commit(false)
  264. statedb.Database().TrieDB().Commit(root, true, nil)
  265. return types.NewBlock(head, nil, nil, nil)
  266. }
  267. // Commit writes the block and state of a genesis specification to the database.
  268. // The block is committed as the canonical head block.
  269. func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
  270. block := g.ToBlock(db)
  271. if block.Number().Sign() != 0 {
  272. return nil, fmt.Errorf("can't commit genesis block with number > 0")
  273. }
  274. config := g.Config
  275. if config == nil {
  276. config = params.AllEthashProtocolChanges
  277. }
  278. if err := config.CheckConfigForkOrder(); err != nil {
  279. return nil, err
  280. }
  281. rawdb.WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty)
  282. rawdb.WriteBlock(db, block)
  283. rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
  284. rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
  285. rawdb.WriteHeadBlockHash(db, block.Hash())
  286. rawdb.WriteHeadFastBlockHash(db, block.Hash())
  287. rawdb.WriteHeadHeaderHash(db, block.Hash())
  288. rawdb.WriteChainConfig(db, block.Hash(), config)
  289. return block, nil
  290. }
  291. // MustCommit writes the genesis block and state to db, panicking on error.
  292. // The block is committed as the canonical head block.
  293. func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
  294. block, err := g.Commit(db)
  295. if err != nil {
  296. panic(err)
  297. }
  298. return block
  299. }
  300. // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
  301. func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
  302. g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
  303. return g.MustCommit(db)
  304. }
  305. // DefaultGenesisBlock returns the Ethereum main net genesis block.
  306. func DefaultGenesisBlock() *Genesis {
  307. return &Genesis{
  308. Config: params.MainnetChainConfig,
  309. Nonce: 66,
  310. ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
  311. GasLimit: 5000,
  312. Difficulty: big.NewInt(17179869184),
  313. Alloc: decodePrealloc(mainnetAllocData),
  314. }
  315. }
  316. // DefaultRopstenGenesisBlock returns the Ropsten network genesis block.
  317. func DefaultRopstenGenesisBlock() *Genesis {
  318. return &Genesis{
  319. Config: params.RopstenChainConfig,
  320. Nonce: 66,
  321. ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
  322. GasLimit: 16777216,
  323. Difficulty: big.NewInt(1048576),
  324. Alloc: decodePrealloc(ropstenAllocData),
  325. }
  326. }
  327. // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
  328. func DefaultRinkebyGenesisBlock() *Genesis {
  329. return &Genesis{
  330. Config: params.RinkebyChainConfig,
  331. Timestamp: 1492009146,
  332. ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
  333. GasLimit: 4700000,
  334. Difficulty: big.NewInt(1),
  335. Alloc: decodePrealloc(rinkebyAllocData),
  336. }
  337. }
  338. // DefaultGoerliGenesisBlock returns the Görli network genesis block.
  339. func DefaultGoerliGenesisBlock() *Genesis {
  340. return &Genesis{
  341. Config: params.GoerliChainConfig,
  342. Timestamp: 1548854791,
  343. ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
  344. GasLimit: 10485760,
  345. Difficulty: big.NewInt(1),
  346. Alloc: decodePrealloc(goerliAllocData),
  347. }
  348. }
  349. func DefaultYoloV1GenesisBlock() *Genesis {
  350. return &Genesis{
  351. Config: params.YoloV1ChainConfig,
  352. Timestamp: 0x5ed754f1,
  353. ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000008a37866fd3627c9205a37c8685666f32ec07bb1b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
  354. GasLimit: 0x47b760,
  355. Difficulty: big.NewInt(1),
  356. Alloc: decodePrealloc(yoloV1AllocData),
  357. }
  358. }
  359. // DeveloperGenesisBlock returns the 'geth --dev' genesis block.
  360. func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
  361. // Override the default period to the user requested one
  362. config := *params.AllCliqueProtocolChanges
  363. config.Clique.Period = period
  364. // Assemble and return the genesis with the precompiles and faucet pre-funded
  365. return &Genesis{
  366. Config: &config,
  367. ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...),
  368. GasLimit: 11500000,
  369. Difficulty: big.NewInt(1),
  370. Alloc: map[common.Address]GenesisAccount{
  371. common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
  372. common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
  373. common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
  374. common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
  375. common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
  376. common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
  377. common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
  378. common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
  379. common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b
  380. faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
  381. },
  382. }
  383. }
  384. func decodePrealloc(data string) GenesisAlloc {
  385. var p []struct{ Addr, Balance *big.Int }
  386. if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
  387. panic(err)
  388. }
  389. ga := make(GenesisAlloc, len(p))
  390. for _, account := range p {
  391. ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
  392. }
  393. return ga
  394. }