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