genesis.go 17 KB

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