github.com/bearnetworkchain/go-bearnetwork@v1.10.19-0.20220604150648-d63890c2e42b/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/bearnetworkchain/go-bearnetwork/common" 29 "github.com/bearnetworkchain/go-bearnetwork/common/hexutil" 30 "github.com/bearnetworkchain/go-bearnetwork/common/math" 31 "github.com/bearnetworkchain/go-bearnetwork/core/rawdb" 32 "github.com/bearnetworkchain/go-bearnetwork/core/state" 33 "github.com/bearnetworkchain/go-bearnetwork/core/types" 34 "github.com/bearnetworkchain/go-bearnetwork/crypto" 35 "github.com/bearnetworkchain/go-bearnetwork/ethdb" 36 "github.com/bearnetworkchain/go-bearnetwork/log" 37 "github.com/bearnetworkchain/go-bearnetwork/params" 38 "github.com/bearnetworkchain/go-bearnetwork/rlp" 39 "github.com/bearnetworkchain/go-bearnetwork/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, overrideArrowGlacier, overrideTerminalTotalDifficulty *big.Int) (*params.ChainConfig, common.Hash, error) { 237 if genesis != nil && genesis.Config == nil { 238 return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig 239 } 240 // Just commit the new block if there is no stored genesis block. 241 stored := rawdb.ReadCanonicalHash(db, 0) 242 if (stored == common.Hash{}) { 243 if genesis == nil { 244 log.Info("Writing default main-net genesis block") 245 genesis = DefaultGenesisBlock() 246 } else { 247 log.Info("Writing custom genesis block") 248 } 249 block, err := genesis.Commit(db) 250 if err != nil { 251 return genesis.Config, common.Hash{}, err 252 } 253 return genesis.Config, block.Hash(), nil 254 } 255 // We have the genesis block in database(perhaps in ancient database) 256 // but the corresponding state is missing. 257 header := rawdb.ReadHeader(db, stored, 0) 258 if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, nil), nil); err != nil { 259 if genesis == nil { 260 genesis = DefaultGenesisBlock() 261 } 262 // Ensure the stored genesis matches with the given one. 263 hash := genesis.ToBlock(nil).Hash() 264 if hash != stored { 265 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 266 } 267 block, err := genesis.Commit(db) 268 if err != nil { 269 return genesis.Config, hash, err 270 } 271 return genesis.Config, block.Hash(), nil 272 } 273 // Check whether the genesis block is already written. 274 if genesis != nil { 275 hash := genesis.ToBlock(nil).Hash() 276 if hash != stored { 277 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 278 } 279 } 280 // Get the existing chain configuration. 281 newcfg := genesis.configOrDefault(stored) 282 if overrideArrowGlacier != nil { 283 newcfg.ArrowGlacierBlock = overrideArrowGlacier 284 } 285 if overrideTerminalTotalDifficulty != nil { 286 newcfg.TerminalTotalDifficulty = overrideTerminalTotalDifficulty 287 } 288 if err := newcfg.CheckConfigForkOrder(); err != nil { 289 return newcfg, common.Hash{}, err 290 } 291 storedcfg := rawdb.ReadChainConfig(db, stored) 292 if storedcfg == nil { 293 log.Warn("Found genesis block without chain config") 294 rawdb.WriteChainConfig(db, stored, newcfg) 295 return newcfg, stored, nil 296 } 297 // Special case: if a private network is being used (no genesis and also no 298 // mainnet hash in the database), we must not apply the `configOrDefault` 299 // chain config as that would be AllProtocolChanges (applying any new fork 300 // on top of an existing private network genesis block). In that case, only 301 // apply the overrides. 302 if genesis == nil && stored != params.MainnetGenesisHash { 303 newcfg = storedcfg 304 if overrideArrowGlacier != nil { 305 newcfg.ArrowGlacierBlock = overrideArrowGlacier 306 } 307 if overrideTerminalTotalDifficulty != nil { 308 newcfg.TerminalTotalDifficulty = overrideTerminalTotalDifficulty 309 } 310 } 311 // Check config compatibility and write the config. Compatibility errors 312 // are returned to the caller unless we're already at block zero. 313 height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db)) 314 if height == nil { 315 return newcfg, stored, fmt.Errorf("missing block number for head header hash") 316 } 317 compatErr := storedcfg.CheckCompatible(newcfg, *height) 318 if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 { 319 return newcfg, stored, compatErr 320 } 321 rawdb.WriteChainConfig(db, stored, newcfg) 322 return newcfg, stored, nil 323 } 324 325 func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig { 326 switch { 327 case g != nil: 328 return g.Config 329 case ghash == params.MainnetGenesisHash: 330 return params.MainnetChainConfig 331 case ghash == params.RopstenGenesisHash: 332 return params.RopstenChainConfig 333 case ghash == params.SepoliaGenesisHash: 334 return params.SepoliaChainConfig 335 case ghash == params.RinkebyGenesisHash: 336 return params.RinkebyChainConfig 337 case ghash == params.GoerliGenesisHash: 338 return params.GoerliChainConfig 339 case ghash == params.KilnGenesisHash: 340 return DefaultKilnGenesisBlock().Config 341 default: 342 return params.AllEthashProtocolChanges 343 } 344 } 345 346 // ToBlock creates the genesis block and writes state of a genesis specification 347 // to the given database (or discards it if nil). 348 func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { 349 if db == nil { 350 db = rawdb.NewMemoryDatabase() 351 } 352 root, err := g.Alloc.flush(db) 353 if err != nil { 354 panic(err) 355 } 356 head := &types.Header{ 357 Number: new(big.Int).SetUint64(g.Number), 358 Nonce: types.EncodeNonce(g.Nonce), 359 Time: g.Timestamp, 360 ParentHash: g.ParentHash, 361 Extra: g.ExtraData, 362 GasLimit: g.GasLimit, 363 GasUsed: g.GasUsed, 364 BaseFee: g.BaseFee, 365 Difficulty: g.Difficulty, 366 MixDigest: g.Mixhash, 367 Coinbase: g.Coinbase, 368 Root: root, 369 } 370 if g.GasLimit == 0 { 371 head.GasLimit = params.GenesisGasLimit 372 } 373 if g.Difficulty == nil && g.Mixhash == (common.Hash{}) { 374 head.Difficulty = params.GenesisDifficulty 375 } 376 if g.Config != nil && g.Config.IsLondon(common.Big0) { 377 if g.BaseFee != nil { 378 head.BaseFee = g.BaseFee 379 } else { 380 head.BaseFee = new(big.Int).SetUint64(params.InitialBaseFee) 381 } 382 } 383 return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil)) 384 } 385 386 // Commit writes the block and state of a genesis specification to the database. 387 // The block is committed as the canonical head block. 388 func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) { 389 block := g.ToBlock(db) 390 if block.Number().Sign() != 0 { 391 return nil, errors.New("can't commit genesis block with number > 0") 392 } 393 config := g.Config 394 if config == nil { 395 config = params.AllEthashProtocolChanges 396 } 397 if err := config.CheckConfigForkOrder(); err != nil { 398 return nil, err 399 } 400 if config.Clique != nil && len(block.Extra()) < 32+crypto.SignatureLength { 401 return nil, errors.New("can't start clique chain without signers") 402 } 403 if err := g.Alloc.write(db, block.Hash()); err != nil { 404 return nil, err 405 } 406 rawdb.WriteTd(db, block.Hash(), block.NumberU64(), block.Difficulty()) 407 rawdb.WriteBlock(db, block) 408 rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil) 409 rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64()) 410 rawdb.WriteHeadBlockHash(db, block.Hash()) 411 rawdb.WriteHeadFastBlockHash(db, block.Hash()) 412 rawdb.WriteHeadHeaderHash(db, block.Hash()) 413 rawdb.WriteChainConfig(db, block.Hash(), config) 414 return block, nil 415 } 416 417 // MustCommit writes the genesis block and state to db, panicking on error. 418 // The block is committed as the canonical head block. 419 func (g *Genesis) MustCommit(db ethdb.Database) *types.Block { 420 block, err := g.Commit(db) 421 if err != nil { 422 panic(err) 423 } 424 return block 425 } 426 427 // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. 428 func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block { 429 g := Genesis{ 430 Alloc: GenesisAlloc{addr: {Balance: balance}}, 431 BaseFee: big.NewInt(params.InitialBaseFee), 432 } 433 return g.MustCommit(db) 434 } 435 436 // DefaultGenesisBlock returns the Ethereum main net genesis block. 437 func DefaultGenesisBlock() *Genesis { 438 return &Genesis{ 439 Config: params.MainnetChainConfig, 440 Nonce: 66, 441 ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), 442 GasLimit: 5000, 443 Difficulty: big.NewInt(17179869184), 444 Alloc: decodePrealloc(mainnetAllocData), 445 } 446 } 447 448 // DefaultRopstenGenesisBlock returns the Ropsten network genesis block. 449 func DefaultRopstenGenesisBlock() *Genesis { 450 return &Genesis{ 451 Config: params.RopstenChainConfig, 452 Nonce: 66, 453 ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"), 454 GasLimit: 16777216, 455 Difficulty: big.NewInt(1048576), 456 Alloc: decodePrealloc(ropstenAllocData), 457 } 458 } 459 460 // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block. 461 func DefaultRinkebyGenesisBlock() *Genesis { 462 return &Genesis{ 463 Config: params.RinkebyChainConfig, 464 Timestamp: 1492009146, 465 ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 466 GasLimit: 4700000, 467 Difficulty: big.NewInt(1), 468 Alloc: decodePrealloc(rinkebyAllocData), 469 } 470 } 471 472 // DefaultGoerliGenesisBlock returns the Görli network genesis block. 473 func DefaultGoerliGenesisBlock() *Genesis { 474 return &Genesis{ 475 Config: params.GoerliChainConfig, 476 Timestamp: 1548854791, 477 ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 478 GasLimit: 10485760, 479 Difficulty: big.NewInt(1), 480 Alloc: decodePrealloc(goerliAllocData), 481 } 482 } 483 484 // DefaultSepoliaGenesisBlock returns the Sepolia network genesis block. 485 func DefaultSepoliaGenesisBlock() *Genesis { 486 return &Genesis{ 487 Config: params.SepoliaChainConfig, 488 Nonce: 0, 489 ExtraData: []byte("Sepolia, Athens, Attica, Greece!"), 490 GasLimit: 0x1c9c380, 491 Difficulty: big.NewInt(0x20000), 492 Timestamp: 1633267481, 493 Alloc: decodePrealloc(sepoliaAllocData), 494 } 495 } 496 497 func DefaultKilnGenesisBlock() *Genesis { 498 g := new(Genesis) 499 reader := strings.NewReader(KilnAllocData) 500 if err := json.NewDecoder(reader).Decode(g); err != nil { 501 panic(err) 502 } 503 return g 504 } 505 506 // DeveloperGenesisBlock returns the 'geth --dev' genesis block. 507 func DeveloperGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *Genesis { 508 // Override the default period to the user requested one 509 config := *params.AllCliqueProtocolChanges 510 config.Clique = ¶ms.CliqueConfig{ 511 Period: period, 512 Epoch: config.Clique.Epoch, 513 } 514 515 // Assemble and return the genesis with the precompiles and faucet pre-funded 516 return &Genesis{ 517 Config: &config, 518 ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), 519 GasLimit: gasLimit, 520 BaseFee: big.NewInt(params.InitialBaseFee), 521 Difficulty: big.NewInt(1), 522 Alloc: map[common.Address]GenesisAccount{ 523 common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover 524 common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 525 common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD 526 common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity 527 common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp 528 common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd 529 common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul 530 common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing 531 common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b 532 faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, 533 }, 534 } 535 } 536 537 func decodePrealloc(data string) GenesisAlloc { 538 var p []struct{ Addr, Balance *big.Int } 539 if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil { 540 panic(err) 541 } 542 ga := make(GenesisAlloc, len(p)) 543 for _, account := range p { 544 ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance} 545 } 546 return ga 547 }