github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/common" 29 "github.com/phillinzzz/newBsc/common/hexutil" 30 "github.com/phillinzzz/newBsc/common/math" 31 "github.com/phillinzzz/newBsc/core/rawdb" 32 "github.com/phillinzzz/newBsc/core/state" 33 "github.com/phillinzzz/newBsc/core/systemcontracts" 34 "github.com/phillinzzz/newBsc/core/types" 35 "github.com/phillinzzz/newBsc/crypto" 36 "github.com/phillinzzz/newBsc/ethdb" 37 "github.com/phillinzzz/newBsc/log" 38 "github.com/phillinzzz/newBsc/params" 39 "github.com/phillinzzz/newBsc/rlp" 40 "github.com/phillinzzz/newBsc/trie" 41 ) 42 43 //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go 44 //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go 45 46 var errGenesisNoConfig = errors.New("genesis has no chain configuration") 47 48 // Genesis specifies the header fields, state of a genesis block. It also defines hard 49 // fork switch-over blocks through the chain configuration. 50 type Genesis struct { 51 Config *params.ChainConfig `json:"config"` 52 Nonce uint64 `json:"nonce"` 53 Timestamp uint64 `json:"timestamp"` 54 ExtraData []byte `json:"extraData"` 55 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 56 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 57 Mixhash common.Hash `json:"mixHash"` 58 Coinbase common.Address `json:"coinbase"` 59 Alloc GenesisAlloc `json:"alloc" gencodec:"required"` 60 61 // These fields are used for consensus tests. Please don't use them 62 // in actual genesis blocks. 63 Number uint64 `json:"number"` 64 GasUsed uint64 `json:"gasUsed"` 65 ParentHash common.Hash `json:"parentHash"` 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 Alloc map[common.UnprefixedAddress]GenesisAccount 102 } 103 104 type genesisAccountMarshaling struct { 105 Code hexutil.Bytes 106 Balance *math.HexOrDecimal256 107 Nonce math.HexOrDecimal64 108 Storage map[storageJSON]storageJSON 109 PrivateKey hexutil.Bytes 110 } 111 112 // storageJSON represents a 256 bit byte array, but allows less than 256 bits when 113 // unmarshaling from hex. 114 type storageJSON common.Hash 115 116 func (h *storageJSON) UnmarshalText(text []byte) error { 117 text = bytes.TrimPrefix(text, []byte("0x")) 118 if len(text) > 64 { 119 return fmt.Errorf("too many hex characters in storage key/value %q", text) 120 } 121 offset := len(h) - len(text)/2 // pad on the left 122 if _, err := hex.Decode(h[offset:], text); err != nil { 123 fmt.Println(err) 124 return fmt.Errorf("invalid hex storage key/value %q", text) 125 } 126 return nil 127 } 128 129 func (h storageJSON) MarshalText() ([]byte, error) { 130 return hexutil.Bytes(h[:]).MarshalText() 131 } 132 133 // GenesisMismatchError is raised when trying to overwrite an existing 134 // genesis block with an incompatible one. 135 type GenesisMismatchError struct { 136 Stored, New common.Hash 137 } 138 139 func (e *GenesisMismatchError) Error() string { 140 return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New) 141 } 142 143 // SetupGenesisBlock writes or updates the genesis block in db. 144 // The block that will be used is: 145 // 146 // genesis == nil genesis != nil 147 // +------------------------------------------ 148 // db has no genesis | main-net default | genesis 149 // db has genesis | from DB | genesis (if compatible) 150 // 151 // The stored chain configuration will be updated if it is compatible (i.e. does not 152 // specify a fork block below the local head block). In case of a conflict, the 153 // error is a *params.ConfigCompatError and the new, unwritten config is returned. 154 // 155 // The returned chain configuration is never nil. 156 func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) { 157 return SetupGenesisBlockWithOverride(db, genesis, nil) 158 } 159 160 func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, overrideBerlin *big.Int) (*params.ChainConfig, common.Hash, error) { 161 if genesis != nil && genesis.Config == nil { 162 return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig 163 } 164 // Just commit the new block if there is no stored genesis block. 165 stored := rawdb.ReadCanonicalHash(db, 0) 166 systemcontracts.GenesisHash = stored 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 if _, err := state.New(header.Root, state.NewDatabaseWithConfigAndCache(db, nil), nil); err != nil { 184 if genesis == nil { 185 genesis = DefaultGenesisBlock() 186 } 187 // Ensure the stored genesis matches with the given one. 188 hash := genesis.ToBlock(nil).Hash() 189 if hash != stored { 190 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 191 } 192 block, err := genesis.Commit(db) 193 if err != nil { 194 return genesis.Config, hash, err 195 } 196 return genesis.Config, block.Hash(), nil 197 } 198 // Check whether the genesis block is already written. 199 if genesis != nil { 200 hash := genesis.ToBlock(nil).Hash() 201 if hash != stored { 202 return genesis.Config, hash, &GenesisMismatchError{stored, hash} 203 } 204 } 205 // Get the existing chain configuration. 206 newcfg := genesis.configOrDefault(stored) 207 if overrideBerlin != nil { 208 newcfg.BerlinBlock = overrideBerlin 209 } 210 if err := newcfg.CheckConfigForkOrder(); err != nil { 211 return newcfg, common.Hash{}, err 212 } 213 storedcfg := rawdb.ReadChainConfig(db, stored) 214 if storedcfg == nil { 215 log.Warn("Found genesis block without chain config") 216 rawdb.WriteChainConfig(db, stored, newcfg) 217 return newcfg, stored, nil 218 } 219 // Special case: don't change the existing config of a non-mainnet chain if no new 220 // config is supplied. These chains would get AllProtocolChanges (and a compat error) 221 // if we just continued here. 222 // The full node of two BSC testnets may run without genesis file after been inited. 223 if genesis == nil && stored != params.MainnetGenesisHash && 224 stored != params.ChapelGenesisHash && stored != params.RialtoGenesisHash && stored != params.BSCGenesisHash { 225 return storedcfg, stored, nil 226 } 227 // Check config compatibility and write the config. Compatibility errors 228 // are returned to the caller unless we're already at block zero. 229 height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db)) 230 if height == nil { 231 return newcfg, stored, fmt.Errorf("missing block number for head header hash") 232 } 233 compatErr := storedcfg.CheckCompatible(newcfg, *height) 234 if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 { 235 return newcfg, stored, compatErr 236 } 237 rawdb.WriteChainConfig(db, stored, newcfg) 238 return newcfg, stored, nil 239 } 240 241 func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig { 242 switch { 243 case g != nil: 244 return g.Config 245 case ghash == params.MainnetGenesisHash: 246 return params.MainnetChainConfig 247 case ghash == params.RopstenGenesisHash: 248 return params.RopstenChainConfig 249 case ghash == params.RinkebyGenesisHash: 250 return params.RinkebyChainConfig 251 case ghash == params.GoerliGenesisHash: 252 return params.GoerliChainConfig 253 case ghash == params.BSCGenesisHash: 254 return params.BSCChainConfig 255 case ghash == params.ChapelGenesisHash: 256 return params.ChapelChainConfig 257 case ghash == params.RialtoGenesisHash: 258 return params.RialtoChainConfig 259 case ghash == params.YoloV3GenesisHash: 260 return params.YoloV3ChainConfig 261 default: 262 return params.AllEthashProtocolChanges 263 } 264 } 265 266 // ToBlock creates the genesis block and writes state of a genesis specification 267 // to the given database (or discards it if nil). 268 func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { 269 if db == nil { 270 db = rawdb.NewMemoryDatabase() 271 } 272 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db), nil) 273 for addr, account := range g.Alloc { 274 statedb.AddBalance(addr, account.Balance) 275 statedb.SetCode(addr, account.Code) 276 statedb.SetNonce(addr, account.Nonce) 277 for key, value := range account.Storage { 278 statedb.SetState(addr, key, value) 279 } 280 } 281 root := statedb.IntermediateRoot(false) 282 head := &types.Header{ 283 Number: new(big.Int).SetUint64(g.Number), 284 Nonce: types.EncodeNonce(g.Nonce), 285 Time: g.Timestamp, 286 ParentHash: g.ParentHash, 287 Extra: g.ExtraData, 288 GasLimit: g.GasLimit, 289 GasUsed: g.GasUsed, 290 Difficulty: g.Difficulty, 291 MixDigest: g.Mixhash, 292 Coinbase: g.Coinbase, 293 Root: root, 294 } 295 if g.GasLimit == 0 { 296 head.GasLimit = params.GenesisGasLimit 297 } 298 if g.Difficulty == nil { 299 head.Difficulty = params.GenesisDifficulty 300 } 301 statedb.Commit(false) 302 statedb.Database().TrieDB().Commit(root, true, nil) 303 304 return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil)) 305 } 306 307 // Commit writes the block and state of a genesis specification to the database. 308 // The block is committed as the canonical head block. 309 func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) { 310 block := g.ToBlock(db) 311 if block.Number().Sign() != 0 { 312 return nil, fmt.Errorf("can't commit genesis block with number > 0") 313 } 314 config := g.Config 315 if config == nil { 316 config = params.AllEthashProtocolChanges 317 } 318 if err := config.CheckConfigForkOrder(); err != nil { 319 return nil, err 320 } 321 rawdb.WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty) 322 rawdb.WriteBlock(db, block) 323 rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil) 324 rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64()) 325 rawdb.WriteHeadBlockHash(db, block.Hash()) 326 rawdb.WriteHeadFastBlockHash(db, block.Hash()) 327 rawdb.WriteHeadHeaderHash(db, block.Hash()) 328 rawdb.WriteChainConfig(db, block.Hash(), config) 329 return block, nil 330 } 331 332 // MustCommit writes the genesis block and state to db, panicking on error. 333 // The block is committed as the canonical head block. 334 func (g *Genesis) MustCommit(db ethdb.Database) *types.Block { 335 block, err := g.Commit(db) 336 if err != nil { 337 panic(err) 338 } 339 return block 340 } 341 342 // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. 343 func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block { 344 g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}} 345 return g.MustCommit(db) 346 } 347 348 // DefaultGenesisBlock returns the Ethereum main net genesis block. 349 func DefaultGenesisBlock() *Genesis { 350 return &Genesis{ 351 Config: params.MainnetChainConfig, 352 Nonce: 66, 353 ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), 354 GasLimit: 5000, 355 Difficulty: big.NewInt(17179869184), 356 Alloc: decodePrealloc(mainnetAllocData), 357 } 358 } 359 360 // DefaultRopstenGenesisBlock returns the Ropsten network genesis block. 361 func DefaultRopstenGenesisBlock() *Genesis { 362 return &Genesis{ 363 Config: params.RopstenChainConfig, 364 Nonce: 66, 365 ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"), 366 GasLimit: 16777216, 367 Difficulty: big.NewInt(1048576), 368 Alloc: decodePrealloc(ropstenAllocData), 369 } 370 } 371 372 // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block. 373 func DefaultRinkebyGenesisBlock() *Genesis { 374 return &Genesis{ 375 Config: params.RinkebyChainConfig, 376 Timestamp: 1492009146, 377 ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 378 GasLimit: 4700000, 379 Difficulty: big.NewInt(1), 380 Alloc: decodePrealloc(rinkebyAllocData), 381 } 382 } 383 384 // DefaultGoerliGenesisBlock returns the Görli network genesis block. 385 func DefaultGoerliGenesisBlock() *Genesis { 386 return &Genesis{ 387 Config: params.GoerliChainConfig, 388 Timestamp: 1548854791, 389 ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 390 GasLimit: 10485760, 391 Difficulty: big.NewInt(1), 392 Alloc: decodePrealloc(goerliAllocData), 393 } 394 } 395 396 func DefaultYoloV3GenesisBlock() *Genesis { 397 // Full genesis: https://gist.github.com/holiman/c6ed9269dce28304ad176314caa75e97 398 return &Genesis{ 399 Config: params.YoloV3ChainConfig, 400 Timestamp: 0x6027dd2e, 401 ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000001041afbcb359d5a8dc58c15b2ff51354ff8a217d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 402 GasLimit: 0x47b760, 403 Difficulty: big.NewInt(1), 404 Alloc: decodePrealloc(yoloV3AllocData), 405 } 406 } 407 408 // DeveloperGenesisBlock returns the 'geth --dev' genesis block. 409 func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis { 410 // Override the default period to the user requested one 411 config := *params.AllCliqueProtocolChanges 412 config.Clique.Period = period 413 414 // Assemble and return the genesis with the precompiles and faucet pre-funded 415 return &Genesis{ 416 Config: &config, 417 ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), 418 GasLimit: 11500000, 419 Difficulty: big.NewInt(1), 420 Alloc: map[common.Address]GenesisAccount{ 421 common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover 422 common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 423 common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD 424 common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity 425 common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp 426 common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd 427 common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul 428 common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing 429 common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b 430 faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, 431 }, 432 } 433 } 434 435 func decodePrealloc(data string) GenesisAlloc { 436 var p []struct{ Addr, Balance *big.Int } 437 if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil { 438 panic(err) 439 } 440 ga := make(GenesisAlloc, len(p)) 441 for _, account := range p { 442 ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance} 443 } 444 return ga 445 }