github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/core/genesis.go (about) 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 17 package core 18 19 import ( 20 "bytes" 21 "encoding/hex" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 "strings" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/common/hexutil" 30 "github.com/ethereum/go-ethereum/common/math" 31 "github.com/ethereum/go-ethereum/core/rawdb" 32 "github.com/ethereum/go-ethereum/core/state" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/ethdb" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/params" 38 "github.com/ethereum/go-ethereum/rlp" 39 "github.com/ethereum/go-ethereum/trie" 40 ) 41 42 //go:generate go run github.com/fjl/gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go 43 //go:generate go run github.com/fjl/gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go 44 45 var errGenesisNoConfig = errors.New("genesis has no chain configuration") 46 47 // Genesis specifies the header fields, state of a genesis block. It also defines hard 48 // fork switch-over blocks through the chain configuration. 49 type Genesis struct { 50 Config *params.ChainConfig `json:"config"` 51 Nonce uint64 `json:"nonce"` 52 Timestamp uint64 `json:"timestamp"` 53 ExtraData []byte `json:"extraData"` 54 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 55 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 56 Mixhash common.Hash `json:"mixHash"` 57 Coinbase common.Address `json:"coinbase"` 58 Alloc GenesisAlloc `json:"alloc" gencodec:"required"` 59 60 // These fields are used for consensus tests. Please don't use them 61 // in actual genesis blocks. 62 Number uint64 `json:"number"` 63 GasUsed uint64 `json:"gasUsed"` 64 ParentHash common.Hash `json:"parentHash"` 65 BaseFee *big.Int `json:"baseFeePerGas"` 66 } 67 68 // GenesisAlloc specifies the initial state that is part of the genesis block. 69 type GenesisAlloc map[common.Address]GenesisAccount 70 71 func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error { 72 m := make(map[common.UnprefixedAddress]GenesisAccount) 73 if err := json.Unmarshal(data, &m); err != nil { 74 return err 75 } 76 *ga = make(GenesisAlloc) 77 for addr, a := range m { 78 (*ga)[common.Address(addr)] = a 79 } 80 return nil 81 } 82 83 // flush adds allocated genesis accounts into a fresh new statedb and 84 // commit the state changes into the given database handler. 85 func (ga *GenesisAlloc) flush(db ethdb.Database) (common.Hash, error) { 86 statedb, err := state.New(common.Hash{}, state.NewDatabase(db), nil) 87 if err != nil { 88 return common.Hash{}, err 89 } 90 for addr, account := range *ga { 91 statedb.AddBalance(addr, account.Balance) 92 statedb.SetCode(addr, account.Code) 93 statedb.SetNonce(addr, account.Nonce) 94 for key, value := range account.Storage { 95 statedb.SetState(addr, key, value) 96 } 97 } 98 root, err := statedb.Commit(false) 99 if err != nil { 100 return common.Hash{}, err 101 } 102 err = statedb.Database().TrieDB().Commit(root, true, nil) 103 if err != nil { 104 return common.Hash{}, err 105 } 106 return root, nil 107 } 108 109 // write writes the json marshaled genesis state into database 110 // with the given block hash as the unique identifier. 111 func (ga *GenesisAlloc) write(db ethdb.KeyValueWriter, hash common.Hash) error { 112 blob, err := json.Marshal(ga) 113 if err != nil { 114 return err 115 } 116 rawdb.WriteGenesisState(db, hash, blob) 117 return nil 118 } 119 120 // CommitGenesisState loads the stored genesis state with the given block 121 // hash and commits them into the given database handler. 122 func CommitGenesisState(db ethdb.Database, hash common.Hash) error { 123 var alloc GenesisAlloc 124 blob := rawdb.ReadGenesisState(db, hash) 125 if len(blob) != 0 { 126 if err := alloc.UnmarshalJSON(blob); err != nil { 127 return err 128 } 129 } else { 130 // Genesis allocation is missing and there are several possibilities: 131 // the node is legacy which doesn't persist the genesis allocation or 132 // the persisted allocation is just lost. 133 // - supported networks(mainnet, testnets), recover with defined allocations 134 // - private network, can't recover 135 var genesis *Genesis 136 switch hash { 137 case params.MainnetGenesisHash: 138 genesis = DefaultGenesisBlock() 139 case params.RopstenGenesisHash: 140 genesis = DefaultRopstenGenesisBlock() 141 case params.RinkebyGenesisHash: 142 genesis = DefaultRinkebyGenesisBlock() 143 case params.GoerliGenesisHash: 144 genesis = DefaultGoerliGenesisBlock() 145 case params.SepoliaGenesisHash: 146 genesis = DefaultSepoliaGenesisBlock() 147 } 148 if genesis != nil { 149 alloc = genesis.Alloc 150 } else { 151 return errors.New("not found") 152 } 153 } 154 _, err := alloc.flush(db) 155 return err 156 } 157 158 // GenesisAccount is an account in the state of the genesis block. 159 type GenesisAccount struct { 160 Code []byte `json:"code,omitempty"` 161 Storage map[common.Hash]common.Hash `json:"storage,omitempty"` 162 Balance *big.Int `json:"balance" gencodec:"required"` 163 Nonce uint64 `json:"nonce,omitempty"` 164 PrivateKey []byte `json:"secretKey,omitempty"` // for tests 165 } 166 167 // field type overrides for gencodec 168 type genesisSpecMarshaling struct { 169 Nonce math.HexOrDecimal64 170 Timestamp math.HexOrDecimal64 171 ExtraData hexutil.Bytes 172 GasLimit math.HexOrDecimal64 173 GasUsed math.HexOrDecimal64 174 Number math.HexOrDecimal64 175 Difficulty *math.HexOrDecimal256 176 BaseFee *math.HexOrDecimal256 177 Alloc map[common.UnprefixedAddress]GenesisAccount 178 } 179 180 type genesisAccountMarshaling struct { 181 Code hexutil.Bytes 182 Balance *math.HexOrDecimal256 183 Nonce math.HexOrDecimal64 184 Storage map[storageJSON]storageJSON 185 PrivateKey hexutil.Bytes 186 } 187 188 // storageJSON represents a 256 bit byte array, but allows less than 256 bits when 189 // unmarshaling from hex. 190 type storageJSON common.Hash 191 192 func (h *storageJSON) UnmarshalText(text []byte) error { 193 text = bytes.TrimPrefix(text, []byte("0x")) 194 if len(text) > 64 { 195 return fmt.Errorf("too many hex characters in storage key/value %q", text) 196 } 197 offset := len(h) - len(text)/2 // pad on the left 198 if _, err := hex.Decode(h[offset:], text); err != nil { 199 fmt.Println(err) 200 return fmt.Errorf("invalid hex storage key/value %q", text) 201 } 202 return nil 203 } 204 205 func (h storageJSON) MarshalText() ([]byte, error) { 206 return hexutil.Bytes(h[:]).MarshalText() 207 } 208 209 // GenesisMismatchError is raised when trying to overwrite an existing 210 // genesis block with an incompatible one. 211 type GenesisMismatchError struct { 212 Stored, New common.Hash 213 } 214 215 func (e *GenesisMismatchError) Error() string { 216 return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New) 217 } 218 219 // SetupGenesisBlock writes or updates the genesis block in db. 220 // The block that will be used is: 221 // 222 // genesis == nil genesis != nil 223 // +------------------------------------------ 224 // db has no genesis | main-net default | genesis 225 // db has genesis | from DB | genesis (if compatible) 226 // 227 // The stored chain configuration will be updated if it is compatible (i.e. does not 228 // specify a fork block below the local head block). In case of a conflict, the 229 // error is a *params.ConfigCompatError and the new, unwritten config is returned. 230 // 231 // The returned chain configuration is never nil. 232 func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) { 233 return SetupGenesisBlockWithOverride(db, genesis, nil, nil) 234 } 235 236 func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, overrideGrayGlacier, overrideTerminalTotalDifficulty *big.Int) (*params.ChainConfig, common.Hash, error) { 237 if genesis != nil && genesis.Config == nil { 238 return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig 239 } 240 241 applyOverrides := func(config *params.ChainConfig) { 242 if config != nil { 243 if overrideTerminalTotalDifficulty != nil { 244 config.TerminalTotalDifficulty = overrideTerminalTotalDifficulty 245 } 246 if overrideGrayGlacier != nil { 247 config.GrayGlacierBlock = overrideGrayGlacier 248 } 249 } 250 } 251 252 // Just commit the new block if there is no stored genesis block. 253 stored := rawdb.ReadCanonicalHash(db, 0) 254 if (stored == common.Hash{}) { 255 if genesis == nil { 256 log.Info("Writing default main-net genesis block") 257 genesis = DefaultGenesisBlock() 258 } else { 259 log.Info("Writing custom genesis block") 260 } 261 block, err := genesis.Commit(db) 262 if err != nil { 263 return genesis.Config, common.Hash{}, err 264 } 265 applyOverrides(genesis.Config) 266 return genesis.Config, block.Hash(), nil 267 } 268 // We have the genesis block in database(perhaps in ancient database) 269 // but the corresponding state is missing. 270 header := rawdb.ReadHeader(db, stored, 0) 271 if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, nil), nil); err != nil { 272 if genesis == nil { 273 genesis = DefaultGenesisBlock() 274 } 275 // Ensure the stored genesis matches with the given one. 276 hash := genesis.ToBlock(nil).Hash() 277 if hash != stored { 278 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 279 } 280 block, err := genesis.Commit(db) 281 if err != nil { 282 return genesis.Config, hash, err 283 } 284 applyOverrides(genesis.Config) 285 return genesis.Config, block.Hash(), nil 286 } 287 // Check whether the genesis block is already written. 288 if genesis != nil { 289 hash := genesis.ToBlock(nil).Hash() 290 if hash != stored { 291 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 292 } 293 } 294 // Get the existing chain configuration. 295 newcfg := genesis.configOrDefault(stored) 296 applyOverrides(newcfg) 297 if err := newcfg.CheckConfigForkOrder(); err != nil { 298 return newcfg, common.Hash{}, err 299 } 300 storedcfg := rawdb.ReadChainConfig(db, stored) 301 if storedcfg == nil { 302 log.Warn("Found genesis block without chain config") 303 rawdb.WriteChainConfig(db, stored, newcfg) 304 return newcfg, stored, nil 305 } 306 // Special case: if a private network is being used (no genesis and also no 307 // mainnet hash in the database), we must not apply the `configOrDefault` 308 // chain config as that would be AllProtocolChanges (applying any new fork 309 // on top of an existing private network genesis block). In that case, only 310 // apply the overrides. 311 if genesis == nil && stored != params.MainnetGenesisHash { 312 newcfg = storedcfg 313 applyOverrides(newcfg) 314 } 315 // Check config compatibility and write the config. Compatibility errors 316 // are returned to the caller unless we're already at block zero. 317 height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db)) 318 if height == nil { 319 return newcfg, stored, fmt.Errorf("missing block number for head header hash") 320 } 321 compatErr := storedcfg.CheckCompatible(newcfg, *height) 322 if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 { 323 return newcfg, stored, compatErr 324 } 325 rawdb.WriteChainConfig(db, stored, newcfg) 326 return newcfg, stored, nil 327 } 328 329 func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig { 330 switch { 331 case g != nil: 332 return g.Config 333 case ghash == params.MainnetGenesisHash: 334 return params.MainnetChainConfig 335 case ghash == params.RopstenGenesisHash: 336 return params.RopstenChainConfig 337 case ghash == params.SepoliaGenesisHash: 338 return params.SepoliaChainConfig 339 case ghash == params.RinkebyGenesisHash: 340 return params.RinkebyChainConfig 341 case ghash == params.GoerliGenesisHash: 342 return params.GoerliChainConfig 343 case ghash == params.KilnGenesisHash: 344 return DefaultKilnGenesisBlock().Config 345 default: 346 return params.AllEthashProtocolChanges 347 } 348 } 349 350 // ToBlock creates the genesis block and writes state of a genesis specification 351 // to the given database (or discards it if nil). 352 func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { 353 if db == nil { 354 db = rawdb.NewMemoryDatabase() 355 } 356 root, err := g.Alloc.flush(db) 357 if err != nil { 358 panic(err) 359 } 360 head := &types.Header{ 361 Number: new(big.Int).SetUint64(g.Number), 362 Nonce: types.EncodeNonce(g.Nonce), 363 Time: g.Timestamp, 364 ParentHash: g.ParentHash, 365 Extra: g.ExtraData, 366 GasLimit: g.GasLimit, 367 GasUsed: g.GasUsed, 368 BaseFee: g.BaseFee, 369 Difficulty: g.Difficulty, 370 MixDigest: g.Mixhash, 371 Coinbase: g.Coinbase, 372 Root: root, 373 } 374 if g.GasLimit == 0 { 375 head.GasLimit = params.GenesisGasLimit 376 } 377 if g.Difficulty == nil && g.Mixhash == (common.Hash{}) { 378 head.Difficulty = params.GenesisDifficulty 379 } 380 if g.Config != nil && g.Config.IsLondon(common.Big0) { 381 if g.BaseFee != nil { 382 head.BaseFee = g.BaseFee 383 } else { 384 head.BaseFee = new(big.Int).SetUint64(params.InitialBaseFee) 385 } 386 } 387 return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil)) 388 } 389 390 // Commit writes the block and state of a genesis specification to the database. 391 // The block is committed as the canonical head block. 392 func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) { 393 block := g.ToBlock(db) 394 if block.Number().Sign() != 0 { 395 return nil, errors.New("can't commit genesis block with number > 0") 396 } 397 config := g.Config 398 if config == nil { 399 config = params.AllEthashProtocolChanges 400 } 401 if err := config.CheckConfigForkOrder(); err != nil { 402 return nil, err 403 } 404 if config.Clique != nil && len(block.Extra()) < 32+crypto.SignatureLength { 405 return nil, errors.New("can't start clique chain without signers") 406 } 407 if err := g.Alloc.write(db, block.Hash()); err != nil { 408 return nil, err 409 } 410 WriteHeadBlock(db, block, nil) 411 rawdb.WriteChainConfig(db, block.Hash(), config) 412 return block, nil 413 } 414 415 func WriteHeadBlock(db ethdb.Database, block *types.Block, prevDifficulty *big.Int) { 416 if prevDifficulty == nil { 417 prevDifficulty = common.Big0 418 } 419 rawdb.WriteTd(db, block.Hash(), block.NumberU64(), new(big.Int).Add(prevDifficulty, block.Difficulty())) 420 rawdb.WriteBlock(db, block) 421 rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil) 422 rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64()) 423 rawdb.WriteHeadBlockHash(db, block.Hash()) 424 rawdb.WriteHeadFastBlockHash(db, block.Hash()) 425 rawdb.WriteHeadHeaderHash(db, block.Hash()) 426 } 427 428 // MustCommit writes the genesis block and state to db, panicking on error. 429 // The block is committed as the canonical head block. 430 func (g *Genesis) MustCommit(db ethdb.Database) *types.Block { 431 block, err := g.Commit(db) 432 if err != nil { 433 panic(err) 434 } 435 return block 436 } 437 438 // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. 439 func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block { 440 g := Genesis{ 441 Alloc: GenesisAlloc{addr: {Balance: balance}}, 442 BaseFee: big.NewInt(params.InitialBaseFee), 443 } 444 return g.MustCommit(db) 445 } 446 447 // DefaultGenesisBlock returns the Ethereum main net genesis block. 448 func DefaultGenesisBlock() *Genesis { 449 return &Genesis{ 450 Config: params.MainnetChainConfig, 451 Nonce: 66, 452 ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), 453 GasLimit: 5000, 454 Difficulty: big.NewInt(17179869184), 455 Alloc: decodePrealloc(mainnetAllocData), 456 } 457 } 458 459 // DefaultRopstenGenesisBlock returns the Ropsten network genesis block. 460 func DefaultRopstenGenesisBlock() *Genesis { 461 return &Genesis{ 462 Config: params.RopstenChainConfig, 463 Nonce: 66, 464 ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"), 465 GasLimit: 16777216, 466 Difficulty: big.NewInt(1048576), 467 Alloc: decodePrealloc(ropstenAllocData), 468 } 469 } 470 471 // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block. 472 func DefaultRinkebyGenesisBlock() *Genesis { 473 return &Genesis{ 474 Config: params.RinkebyChainConfig, 475 Timestamp: 1492009146, 476 ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 477 GasLimit: 4700000, 478 Difficulty: big.NewInt(1), 479 Alloc: decodePrealloc(rinkebyAllocData), 480 } 481 } 482 483 // DefaultGoerliGenesisBlock returns the Görli network genesis block. 484 func DefaultGoerliGenesisBlock() *Genesis { 485 return &Genesis{ 486 Config: params.GoerliChainConfig, 487 Timestamp: 1548854791, 488 ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 489 GasLimit: 10485760, 490 Difficulty: big.NewInt(1), 491 Alloc: decodePrealloc(goerliAllocData), 492 } 493 } 494 495 // DefaultSepoliaGenesisBlock returns the Sepolia network genesis block. 496 func DefaultSepoliaGenesisBlock() *Genesis { 497 return &Genesis{ 498 Config: params.SepoliaChainConfig, 499 Nonce: 0, 500 ExtraData: []byte("Sepolia, Athens, Attica, Greece!"), 501 GasLimit: 0x1c9c380, 502 Difficulty: big.NewInt(0x20000), 503 Timestamp: 1633267481, 504 Alloc: decodePrealloc(sepoliaAllocData), 505 } 506 } 507 508 func DefaultKilnGenesisBlock() *Genesis { 509 g := new(Genesis) 510 reader := strings.NewReader(KilnAllocData) 511 if err := json.NewDecoder(reader).Decode(g); err != nil { 512 panic(err) 513 } 514 return g 515 } 516 517 // DeveloperGenesisBlock returns the 'geth --dev' genesis block. 518 func DeveloperGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *Genesis { 519 // Override the default period to the user requested one 520 config := *params.AllCliqueProtocolChanges 521 config.Clique = ¶ms.CliqueConfig{ 522 Period: period, 523 Epoch: config.Clique.Epoch, 524 } 525 526 // Assemble and return the genesis with the precompiles and faucet pre-funded 527 return &Genesis{ 528 Config: &config, 529 ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), 530 GasLimit: gasLimit, 531 BaseFee: big.NewInt(params.InitialBaseFee), 532 Difficulty: big.NewInt(1), 533 Alloc: map[common.Address]GenesisAccount{ 534 common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover 535 common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 536 common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD 537 common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity 538 common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp 539 common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd 540 common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul 541 common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing 542 common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b 543 faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, 544 }, 545 } 546 } 547 548 func decodePrealloc(data string) GenesisAlloc { 549 var p []struct{ Addr, Balance *big.Int } 550 if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil { 551 panic(err) 552 } 553 ga := make(GenesisAlloc, len(p)) 554 for _, account := range p { 555 ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance} 556 } 557 return ga 558 }