github.com/daethereum/go-dae@v2.2.3+incompatible/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/daethereum/go-dae/common" 29 "github.com/daethereum/go-dae/common/hexutil" 30 "github.com/daethereum/go-dae/common/math" 31 "github.com/daethereum/go-dae/core/rawdb" 32 "github.com/daethereum/go-dae/core/state" 33 "github.com/daethereum/go-dae/core/types" 34 "github.com/daethereum/go-dae/crypto" 35 "github.com/daethereum/go-dae/ethdb" 36 "github.com/daethereum/go-dae/log" 37 "github.com/daethereum/go-dae/params" 38 "github.com/daethereum/go-dae/rlp" 39 "github.com/daethereum/go-dae/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 rawdb.WriteTd(db, block.Hash(), block.NumberU64(), block.Difficulty()) 411 rawdb.WriteBlock(db, block) 412 rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil) 413 rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64()) 414 rawdb.WriteHeadBlockHash(db, block.Hash()) 415 rawdb.WriteHeadFastBlockHash(db, block.Hash()) 416 rawdb.WriteHeadHeaderHash(db, block.Hash()) 417 rawdb.WriteChainConfig(db, block.Hash(), config) 418 return block, nil 419 } 420 421 // MustCommit writes the genesis block and state to db, panicking on error. 422 // The block is committed as the canonical head block. 423 func (g *Genesis) MustCommit(db ethdb.Database) *types.Block { 424 block, err := g.Commit(db) 425 if err != nil { 426 panic(err) 427 } 428 return block 429 } 430 431 // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. 432 func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block { 433 g := Genesis{ 434 Alloc: GenesisAlloc{addr: {Balance: balance}}, 435 BaseFee: big.NewInt(params.InitialBaseFee), 436 } 437 return g.MustCommit(db) 438 } 439 440 // DefaultGenesisBlock returns the Ethereum main net genesis block. 441 func DefaultGenesisBlock() *Genesis { 442 return &Genesis{ 443 Config: params.MainnetChainConfig, 444 Nonce: 66, 445 ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), 446 GasLimit: 5000, 447 Difficulty: big.NewInt(17179869184), 448 Alloc: decodePrealloc(mainnetAllocData), 449 } 450 } 451 452 // DefaultRopstenGenesisBlock returns the Ropsten network genesis block. 453 func DefaultRopstenGenesisBlock() *Genesis { 454 return &Genesis{ 455 Config: params.RopstenChainConfig, 456 Nonce: 66, 457 ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"), 458 GasLimit: 16777216, 459 Difficulty: big.NewInt(1048576), 460 Alloc: decodePrealloc(ropstenAllocData), 461 } 462 } 463 464 // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block. 465 func DefaultRinkebyGenesisBlock() *Genesis { 466 return &Genesis{ 467 Config: params.RinkebyChainConfig, 468 Timestamp: 1492009146, 469 ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 470 GasLimit: 4700000, 471 Difficulty: big.NewInt(1), 472 Alloc: decodePrealloc(rinkebyAllocData), 473 } 474 } 475 476 // DefaultGoerliGenesisBlock returns the Görli network genesis block. 477 func DefaultGoerliGenesisBlock() *Genesis { 478 return &Genesis{ 479 Config: params.GoerliChainConfig, 480 Timestamp: 1548854791, 481 ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 482 GasLimit: 10485760, 483 Difficulty: big.NewInt(1), 484 Alloc: decodePrealloc(goerliAllocData), 485 } 486 } 487 488 // DefaultSepoliaGenesisBlock returns the Sepolia network genesis block. 489 func DefaultSepoliaGenesisBlock() *Genesis { 490 return &Genesis{ 491 Config: params.SepoliaChainConfig, 492 Nonce: 0, 493 ExtraData: []byte("Sepolia, Athens, Attica, Greece!"), 494 GasLimit: 0x1c9c380, 495 Difficulty: big.NewInt(0x20000), 496 Timestamp: 1633267481, 497 Alloc: decodePrealloc(sepoliaAllocData), 498 } 499 } 500 501 func DefaultKilnGenesisBlock() *Genesis { 502 g := new(Genesis) 503 reader := strings.NewReader(KilnAllocData) 504 if err := json.NewDecoder(reader).Decode(g); err != nil { 505 panic(err) 506 } 507 return g 508 } 509 510 // DeveloperGenesisBlock returns the 'geth --dev' genesis block. 511 func DeveloperGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *Genesis { 512 // Override the default period to the user requested one 513 config := *params.AllCliqueProtocolChanges 514 config.Clique = ¶ms.CliqueConfig{ 515 Period: period, 516 Epoch: config.Clique.Epoch, 517 } 518 519 // Assemble and return the genesis with the precompiles and faucet pre-funded 520 return &Genesis{ 521 Config: &config, 522 ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), 523 GasLimit: gasLimit, 524 BaseFee: big.NewInt(params.InitialBaseFee), 525 Difficulty: big.NewInt(1), 526 Alloc: map[common.Address]GenesisAccount{ 527 common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover 528 common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 529 common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD 530 common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity 531 common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp 532 common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd 533 common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul 534 common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing 535 common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b 536 faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, 537 }, 538 } 539 } 540 541 func decodePrealloc(data string) GenesisAlloc { 542 var p []struct{ Addr, Balance *big.Int } 543 if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil { 544 panic(err) 545 } 546 ga := make(GenesisAlloc, len(p)) 547 for _, account := range p { 548 ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance} 549 } 550 return ga 551 }