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