github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/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/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/common/hexutil" 30 "github.com/ethereum/go-ethereum/common/math" 31 "github.com/ethereum/go-ethereum/core/state" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/ethdb" 34 "github.com/ethereum/go-ethereum/log" 35 "github.com/ethereum/go-ethereum/params" 36 "github.com/ethereum/go-ethereum/rlp" 37 ) 38 39 //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go 40 //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go 41 42 var errGenesisNoConfig = errors.New("genesis has no chain configuration") 43 44 // Genesis specifies the header fields, state of a genesis block. It also defines hard 45 // fork switch-over blocks through the chain configuration. 46 type Genesis struct { 47 Config *params.ChainConfig `json:"config"` 48 Nonce uint64 `json:"nonce"` 49 Timestamp uint64 `json:"timestamp"` 50 ExtraData []byte `json:"extraData"` 51 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 52 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 53 Mixhash common.Hash `json:"mixHash"` 54 Coinbase common.Address `json:"coinbase"` 55 Alloc GenesisAlloc `json:"alloc" gencodec:"required"` 56 57 // These fields are used for consensus tests. Please don't use them 58 // in actual genesis blocks. 59 Number uint64 `json:"number"` 60 GasUsed uint64 `json:"gasUsed"` 61 ParentHash common.Hash `json:"parentHash"` 62 } 63 64 // GenesisAlloc specifies the initial state that is part of the genesis block. 65 type GenesisAlloc map[common.Address]GenesisAccount 66 67 func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error { 68 m := make(map[common.UnprefixedAddress]GenesisAccount) 69 if err := json.Unmarshal(data, &m); err != nil { 70 return err 71 } 72 *ga = make(GenesisAlloc) 73 for addr, a := range m { 74 (*ga)[common.Address(addr)] = a 75 } 76 return nil 77 } 78 79 // GenesisAccount is an account in the state of the genesis block. 80 type GenesisAccount struct { 81 Code []byte `json:"code,omitempty"` 82 Storage map[common.Hash]common.Hash `json:"storage,omitempty"` 83 Balance *big.Int `json:"balance" gencodec:"required"` 84 Nonce uint64 `json:"nonce,omitempty"` 85 PrivateKey []byte `json:"secretKey,omitempty"` // for tests 86 } 87 88 // field type overrides for gencodec 89 type genesisSpecMarshaling struct { 90 Nonce math.HexOrDecimal64 91 Timestamp math.HexOrDecimal64 92 ExtraData hexutil.Bytes 93 GasLimit math.HexOrDecimal64 94 GasUsed math.HexOrDecimal64 95 Number math.HexOrDecimal64 96 Difficulty *math.HexOrDecimal256 97 Alloc map[common.UnprefixedAddress]GenesisAccount 98 } 99 100 type genesisAccountMarshaling struct { 101 Code hexutil.Bytes 102 Balance *math.HexOrDecimal256 103 Nonce math.HexOrDecimal64 104 Storage map[storageJSON]storageJSON 105 PrivateKey hexutil.Bytes 106 } 107 108 // storageJSON represents a 256 bit byte array, but allows less than 256 bits when 109 // unmarshaling from hex. 110 type storageJSON common.Hash 111 112 func (h *storageJSON) UnmarshalText(text []byte) error { 113 text = bytes.TrimPrefix(text, []byte("0x")) 114 if len(text) > 64 { 115 return fmt.Errorf("too many hex characters in storage key/value %q", text) 116 } 117 offset := len(h) - len(text)/2 // pad on the left 118 if _, err := hex.Decode(h[offset:], text); err != nil { 119 fmt.Println(err) 120 return fmt.Errorf("invalid hex storage key/value %q", text) 121 } 122 return nil 123 } 124 125 func (h storageJSON) MarshalText() ([]byte, error) { 126 return hexutil.Bytes(h[:]).MarshalText() 127 } 128 129 // GenesisMismatchError is raised when trying to overwrite an existing 130 // genesis block with an incompatible one. 131 type GenesisMismatchError struct { 132 Stored, New common.Hash 133 } 134 135 func (e *GenesisMismatchError) Error() string { 136 return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8]) 137 } 138 139 // SetupGenesisBlock writes or updates the genesis block in db. 140 // The block that will be used is: 141 // 142 // genesis == nil genesis != nil 143 // +------------------------------------------ 144 // db has no genesis | main-net default | genesis 145 // db has genesis | from DB | genesis (if compatible) 146 // 147 // The stored chain configuration will be updated if it is compatible (i.e. does not 148 // specify a fork block below the local head block). In case of a conflict, the 149 // error is a *params.ConfigCompatError and the new, unwritten config is returned. 150 // 151 // The returned chain configuration is never nil. 152 func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) { 153 if genesis != nil && genesis.Config == nil { 154 return params.AllProtocolChanges, common.Hash{}, errGenesisNoConfig 155 } 156 157 // Just commit the new block if there is no stored genesis block. 158 stored := GetCanonicalHash(db, 0) 159 if (stored == common.Hash{}) { 160 if genesis == nil { 161 log.Info("Writing default main-net genesis block") 162 genesis = DefaultGenesisBlock() 163 } else { 164 log.Info("Writing custom genesis block") 165 } 166 block, err := genesis.Commit(db) 167 return genesis.Config, block.Hash(), err 168 } 169 170 // Check whether the genesis block is already written. 171 if genesis != nil { 172 block, _ := genesis.ToBlock() 173 hash := block.Hash() 174 if hash != stored { 175 return genesis.Config, block.Hash(), &GenesisMismatchError{stored, hash} 176 } 177 } 178 179 // Get the existing chain configuration. 180 newcfg := genesis.configOrDefault(stored) 181 storedcfg, err := GetChainConfig(db, stored) 182 if err != nil { 183 if err == ErrChainConfigNotFound { 184 // This case happens if a genesis write was interrupted. 185 log.Warn("Found genesis block without chain config") 186 err = WriteChainConfig(db, stored, newcfg) 187 } 188 return newcfg, stored, err 189 } 190 // Special case: don't change the existing config of a non-mainnet chain if no new 191 // config is supplied. These chains would get AllProtocolChanges (and a compat error) 192 // if we just continued here. 193 if genesis == nil && stored != params.MainnetGenesisHash { 194 return storedcfg, stored, nil 195 } 196 197 // Check config compatibility and write the config. Compatibility errors 198 // are returned to the caller unless we're already at block zero. 199 height := GetBlockNumber(db, GetHeadHeaderHash(db)) 200 if height == missingNumber { 201 return newcfg, stored, fmt.Errorf("missing block number for head header hash") 202 } 203 compatErr := storedcfg.CheckCompatible(newcfg, height) 204 if compatErr != nil && height != 0 && compatErr.RewindTo != 0 { 205 return newcfg, stored, compatErr 206 } 207 return newcfg, stored, WriteChainConfig(db, stored, newcfg) 208 } 209 210 func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig { 211 switch { 212 case g != nil: 213 return g.Config 214 case ghash == params.MainnetGenesisHash: 215 return params.MainnetChainConfig 216 case ghash == params.TestnetGenesisHash: 217 return params.TestnetChainConfig 218 default: 219 return params.AllProtocolChanges 220 } 221 } 222 223 // ToBlock creates the block and state of a genesis specification. 224 func (g *Genesis) ToBlock() (*types.Block, *state.StateDB) { 225 db, _ := ethdb.NewMemDatabase() 226 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db)) 227 for addr, account := range g.Alloc { 228 statedb.AddBalance(addr, account.Balance) 229 statedb.SetCode(addr, account.Code) 230 statedb.SetNonce(addr, account.Nonce) 231 for key, value := range account.Storage { 232 statedb.SetState(addr, key, value) 233 } 234 } 235 root := statedb.IntermediateRoot(false) 236 head := &types.Header{ 237 Number: new(big.Int).SetUint64(g.Number), 238 Nonce: types.EncodeNonce(g.Nonce), 239 Time: new(big.Int).SetUint64(g.Timestamp), 240 ParentHash: g.ParentHash, 241 Extra: g.ExtraData, 242 GasLimit: new(big.Int).SetUint64(g.GasLimit), 243 GasUsed: new(big.Int).SetUint64(g.GasUsed), 244 Difficulty: g.Difficulty, 245 MixDigest: g.Mixhash, 246 Coinbase: g.Coinbase, 247 Root: root, 248 } 249 if g.GasLimit == 0 { 250 head.GasLimit = params.GenesisGasLimit 251 } 252 if g.Difficulty == nil { 253 head.Difficulty = params.GenesisDifficulty 254 } 255 return types.NewBlock(head, nil, nil, nil), statedb 256 } 257 258 // Commit writes the block and state of a genesis specification to the database. 259 // The block is committed as the canonical head block. 260 func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) { 261 block, statedb := g.ToBlock() 262 if block.Number().Sign() != 0 { 263 return nil, fmt.Errorf("can't commit genesis block with number > 0") 264 } 265 if _, err := statedb.CommitTo(db, false); err != nil { 266 return nil, fmt.Errorf("cannot write state: %v", err) 267 } 268 if err := WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty); err != nil { 269 return nil, err 270 } 271 if err := WriteBlock(db, block); err != nil { 272 return nil, err 273 } 274 if err := WriteBlockReceipts(db, block.Hash(), block.NumberU64(), nil); err != nil { 275 return nil, err 276 } 277 if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil { 278 return nil, err 279 } 280 if err := WriteHeadBlockHash(db, block.Hash()); err != nil { 281 return nil, err 282 } 283 if err := WriteHeadHeaderHash(db, block.Hash()); err != nil { 284 return nil, err 285 } 286 config := g.Config 287 if config == nil { 288 config = params.AllProtocolChanges 289 } 290 return block, WriteChainConfig(db, block.Hash(), config) 291 } 292 293 // MustCommit writes the genesis block and state to db, panicking on error. 294 // The block is committed as the canonical head block. 295 func (g *Genesis) MustCommit(db ethdb.Database) *types.Block { 296 block, err := g.Commit(db) 297 if err != nil { 298 panic(err) 299 } 300 return block 301 } 302 303 // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. 304 func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block { 305 g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}} 306 return g.MustCommit(db) 307 } 308 309 // DefaultGenesisBlock returns the Ethereum main net genesis block. 310 func DefaultGenesisBlock() *Genesis { 311 return &Genesis{ 312 Config: params.MainnetChainConfig, 313 Nonce: 66, 314 ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), 315 GasLimit: 5000, 316 Difficulty: big.NewInt(17179869184), 317 Alloc: decodePrealloc(mainnetAllocData), 318 } 319 } 320 321 // DefaultTestnetGenesisBlock returns the Ropsten network genesis block. 322 func DefaultTestnetGenesisBlock() *Genesis { 323 return &Genesis{ 324 Config: params.TestnetChainConfig, 325 Nonce: 66, 326 ExtraData: hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"), 327 GasLimit: 16777216, 328 Difficulty: big.NewInt(1048576), 329 Alloc: decodePrealloc(testnetAllocData), 330 } 331 } 332 333 // DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block. 334 func DefaultRinkebyGenesisBlock() *Genesis { 335 return &Genesis{ 336 Config: params.RinkebyChainConfig, 337 Timestamp: 1492009146, 338 ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), 339 GasLimit: 4700000, 340 Difficulty: big.NewInt(1), 341 Alloc: decodePrealloc(rinkebyAllocData), 342 } 343 } 344 345 // DevGenesisBlock returns the 'geth --dev' genesis block. 346 func DevGenesisBlock() *Genesis { 347 return &Genesis{ 348 Config: params.AllProtocolChanges, 349 Nonce: 42, 350 GasLimit: 4712388, 351 Difficulty: big.NewInt(131072), 352 Alloc: decodePrealloc(devAllocData), 353 } 354 } 355 356 func decodePrealloc(data string) GenesisAlloc { 357 var p []struct{ Addr, Balance *big.Int } 358 if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil { 359 panic(err) 360 } 361 ga := make(GenesisAlloc, len(p)) 362 for _, account := range p { 363 ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance} 364 } 365 return ga 366 }