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