genesis.go 14 KB

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