github.com/codingfuture/orig-energi3@v0.8.4/core/genesis.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2014 The go-ethereum Authors
     3  // This file is part of the Energi Core library.
     4  //
     5  // The Energi Core library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The Energi Core library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package core
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/hex"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  	"os"
    28  	"strings"
    29  
    30  	"github.com/ethereum/go-ethereum/accounts/abi"
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/common/hexutil"
    33  	"github.com/ethereum/go-ethereum/common/math"
    34  	"github.com/ethereum/go-ethereum/core/rawdb"
    35  	"github.com/ethereum/go-ethereum/core/state"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/core/vm"
    38  	"github.com/ethereum/go-ethereum/ethdb"
    39  	"github.com/ethereum/go-ethereum/log"
    40  	"github.com/ethereum/go-ethereum/params"
    41  	"github.com/ethereum/go-ethereum/rlp"
    42  
    43  	energi_abi "energi.world/core/gen3/energi/abi"
    44  	energi_params "energi.world/core/gen3/energi/params"
    45  )
    46  
    47  //go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
    48  //go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go
    49  //go:generate gencodec -type GenesisXfer -field-override genesisXferMarshaling -out gen_genesis_xfer.go
    50  var errGenesisNoConfig = errors.New("genesis has no chain configuration")
    51  
    52  // Genesis specifies the header fields, state of a genesis block. It also defines hard
    53  // fork switch-over blocks through the chain configuration.
    54  type Genesis struct {
    55  	Config     *params.ChainConfig `json:"config"`
    56  	Nonce      uint64              `json:"nonce"`
    57  	Timestamp  uint64              `json:"timestamp"`
    58  	ExtraData  []byte              `json:"extraData"`
    59  	GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
    60  	Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
    61  	Mixhash    common.Hash         `json:"mixHash"`
    62  	Coinbase   common.Address      `json:"coinbase"`
    63  	Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`
    64  	Xfers      GenesisXfers        `json:"xfers"`
    65  
    66  	// These fields are used for consensus tests. Please don't use them
    67  	// in actual genesis blocks.
    68  	Number     uint64      `json:"number"`
    69  	GasUsed    uint64      `json:"gasUsed"`
    70  	ParentHash common.Hash `json:"parentHash"`
    71  }
    72  
    73  // GenesisAlloc specifies the initial state that is part of the genesis block.
    74  type GenesisAlloc map[common.Address]GenesisAccount
    75  
    76  func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
    77  	m := make(map[common.UnprefixedAddress]GenesisAccount)
    78  	if err := json.Unmarshal(data, &m); err != nil {
    79  		return err
    80  	}
    81  	*ga = make(GenesisAlloc)
    82  	for addr, a := range m {
    83  		(*ga)[common.Address(addr)] = a
    84  	}
    85  	return nil
    86  }
    87  
    88  // GenesisAccount is an account in the state of the genesis block.
    89  type GenesisAccount struct {
    90  	Code       []byte                      `json:"code,omitempty"`
    91  	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
    92  	Balance    *big.Int                    `json:"balance" gencodec:"required"`
    93  	Nonce      uint64                      `json:"nonce,omitempty"`
    94  	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
    95  }
    96  
    97  type GenesisXfers []GenesisXfer
    98  
    99  type GenesisXfer struct {
   100  	Addr  common.Address `json:"addr" gencodec:"required"`
   101  	Code  []byte         `json:"code" gencodec:"required"`
   102  	Value *big.Int       `json:"value,omitempty"`
   103  }
   104  
   105  // field type overrides for gencodec
   106  type genesisSpecMarshaling struct {
   107  	Nonce      math.HexOrDecimal64
   108  	Timestamp  math.HexOrDecimal64
   109  	ExtraData  hexutil.Bytes
   110  	GasLimit   math.HexOrDecimal64
   111  	GasUsed    math.HexOrDecimal64
   112  	Number     math.HexOrDecimal64
   113  	Difficulty *math.HexOrDecimal256
   114  	Alloc      map[common.UnprefixedAddress]GenesisAccount
   115  }
   116  
   117  type genesisAccountMarshaling struct {
   118  	Code       hexutil.Bytes
   119  	Balance    *math.HexOrDecimal256
   120  	Nonce      math.HexOrDecimal64
   121  	Storage    map[storageJSON]storageJSON
   122  	PrivateKey hexutil.Bytes
   123  }
   124  
   125  type genesisXferMarshaling struct {
   126  	Addr  common.UnprefixedAddress
   127  	Code  hexutil.Bytes
   128  	Value *math.HexOrDecimal256
   129  }
   130  
   131  // storageJSON represents a 256 bit byte array, but allows less than 256 bits when
   132  // unmarshaling from hex.
   133  type storageJSON common.Hash
   134  
   135  func (h *storageJSON) UnmarshalText(text []byte) error {
   136  	text = bytes.TrimPrefix(text, []byte("0x"))
   137  	if len(text) > 64 {
   138  		return fmt.Errorf("too many hex characters in storage key/value %q", text)
   139  	}
   140  	offset := len(h) - len(text)/2 // pad on the left
   141  	if _, err := hex.Decode(h[offset:], text); err != nil {
   142  		fmt.Println(err)
   143  		return fmt.Errorf("invalid hex storage key/value %q", text)
   144  	}
   145  	return nil
   146  }
   147  
   148  func (h storageJSON) MarshalText() ([]byte, error) {
   149  	return hexutil.Bytes(h[:]).MarshalText()
   150  }
   151  
   152  // GenesisMismatchError is raised when trying to overwrite an existing
   153  // genesis block with an incompatible one.
   154  type GenesisMismatchError struct {
   155  	Stored, New common.Hash
   156  }
   157  
   158  func (e *GenesisMismatchError) Error() string {
   159  	return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8])
   160  }
   161  
   162  // SetupGenesisBlock writes or updates the genesis block in db.
   163  // The block that will be used is:
   164  //
   165  //                          genesis == nil       genesis != nil
   166  //                       +------------------------------------------
   167  //     db has no genesis |  main-net default  |  genesis
   168  //     db has genesis    |  from DB           |  genesis (if compatible)
   169  //
   170  // The stored chain configuration will be updated if it is compatible (i.e. does not
   171  // specify a fork block below the local head block). In case of a conflict, the
   172  // error is a *params.ConfigCompatError and the new, unwritten config is returned.
   173  //
   174  // The returned chain configuration is never nil.
   175  func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
   176  	return SetupGenesisBlockWithOverride(db, genesis, nil)
   177  }
   178  func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, constantinopleOverride *big.Int) (*params.ChainConfig, common.Hash, error) {
   179  	if genesis != nil && genesis.Config == nil {
   180  		return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
   181  	}
   182  	// Just commit the new block if there is no stored genesis block.
   183  	stored := rawdb.ReadCanonicalHash(db, 0)
   184  	if (stored == common.Hash{}) {
   185  		if genesis == nil {
   186  			log.Info("Writing default main-net genesis block")
   187  			genesis = DefaultGenesisBlock()
   188  		} else {
   189  			log.Info("Writing custom genesis block")
   190  		}
   191  		block, err := genesis.Commit(db)
   192  		return genesis.Config, block.Hash(), err
   193  	}
   194  
   195  	// Check whether the genesis block is already written.
   196  	if genesis != nil {
   197  		hash := genesis.ToBlock(nil).Hash()
   198  		if hash != stored {
   199  			return genesis.Config, hash, &GenesisMismatchError{stored, hash}
   200  		}
   201  	}
   202  
   203  	// Get the existing chain configuration.
   204  	newcfg := genesis.configOrDefault(stored)
   205  	if constantinopleOverride != nil {
   206  		newcfg.ConstantinopleBlock = constantinopleOverride
   207  		newcfg.PetersburgBlock = constantinopleOverride
   208  	}
   209  	storedcfg := rawdb.ReadChainConfig(db, stored)
   210  	if storedcfg == nil {
   211  		log.Warn("Found genesis block without chain config")
   212  		rawdb.WriteChainConfig(db, stored, newcfg)
   213  		return newcfg, stored, nil
   214  	}
   215  	// Special case: don't change the existing config of a non-mainnet chain if no new
   216  	// config is supplied. These chains would get AllProtocolChanges (and a compat error)
   217  	// if we just continued here.
   218  	if genesis == nil && stored != params.MainnetGenesisHash {
   219  		return storedcfg, stored, nil
   220  	}
   221  
   222  	// Check config compatibility and write the config. Compatibility errors
   223  	// are returned to the caller unless we're already at block zero.
   224  	height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
   225  	if height == nil {
   226  		return newcfg, stored, fmt.Errorf("missing block number for head header hash")
   227  	}
   228  	compatErr := storedcfg.CheckCompatible(newcfg, *height)
   229  	if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
   230  		return newcfg, stored, compatErr
   231  	}
   232  	rawdb.WriteChainConfig(db, stored, newcfg)
   233  	return newcfg, stored, nil
   234  }
   235  
   236  func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
   237  	switch {
   238  	case g != nil:
   239  		return g.Config
   240  	case ghash == params.MainnetGenesisHash:
   241  		return params.EnergiMainnetChainConfig
   242  	case ghash == params.TestnetGenesisHash:
   243  		return params.EnergiTestnetChainConfig
   244  	default:
   245  		return params.AllEthashProtocolChanges
   246  	}
   247  }
   248  
   249  // ToBlock creates the genesis block and writes state of a genesis specification
   250  // to the given database (or discards it if nil).
   251  func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
   252  	if db == nil {
   253  		db = ethdb.NewMemDatabase()
   254  	}
   255  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
   256  	for addr, account := range g.Alloc {
   257  		statedb.AddBalance(addr, account.Balance)
   258  		statedb.SetCode(addr, account.Code)
   259  		statedb.SetNonce(addr, account.Nonce)
   260  		for key, value := range account.Storage {
   261  			statedb.SetState(addr, key, value)
   262  		}
   263  	}
   264  	root := statedb.IntermediateRoot(false)
   265  	head := &types.Header{
   266  		Number:     new(big.Int).SetUint64(g.Number),
   267  		Nonce:      types.EncodeNonce(g.Nonce),
   268  		Time:       g.Timestamp,
   269  		ParentHash: g.ParentHash,
   270  		Extra:      g.ExtraData,
   271  		GasLimit:   g.GasLimit,
   272  		GasUsed:    g.GasUsed,
   273  		Difficulty: g.Difficulty,
   274  		MixDigest:  g.Mixhash,
   275  		Coinbase:   g.Coinbase,
   276  		Root:       root,
   277  	}
   278  	if g.GasLimit == 0 {
   279  		head.GasLimit = params.GenesisGasLimit
   280  	}
   281  	if g.Difficulty == nil {
   282  		head.Difficulty = params.GenesisDifficulty
   283  	}
   284  
   285  	// Process transactions, but do not really record them in Genesis
   286  	//---
   287  	if config := g.Config; config != nil {
   288  		debug := false
   289  		author := energi_params.Energi_TreasuryV1
   290  		gasLimit := uint64(100000000)
   291  		gp := new(GasPool)
   292  
   293  		systemFaucet := energi_params.Energi_SystemFaucet
   294  		statedb.SetBalance(systemFaucet, math.MaxBig256)
   295  
   296  		vmcfg := vm.Config{}
   297  
   298  		if debug {
   299  			vmcfg = vm.Config{
   300  				Debug: true,
   301  				Tracer: vm.NewStructLogger(&vm.LogConfig{
   302  					Debug: true,
   303  				}),
   304  			}
   305  		}
   306  
   307  		for i, tx := range g.Xfers {
   308  			gp.AddGas(gasLimit)
   309  			val := tx.Value
   310  
   311  			if val == nil {
   312  				val = common.Big1
   313  			}
   314  
   315  			msg := types.NewMessage(
   316  				systemFaucet,
   317  				&tx.Addr,
   318  				uint64(i),
   319  				common.Big0,
   320  				gasLimit,
   321  				common.Big0,
   322  				tx.Code,
   323  				false,
   324  			)
   325  			ctx := NewEVMContext(msg, head, nil, &author)
   326  			ctx.GasLimit = gasLimit
   327  			evm := vm.NewEVM(ctx, statedb, g.Config, vmcfg)
   328  			sttrans := NewStateTransition(evm, msg, gp)
   329  			sttrans.inSetup = true
   330  			_, _, _, err := sttrans.TransitionDb()
   331  			if err != nil {
   332  				panic(fmt.Errorf("invalid transaction: %v", err))
   333  			}
   334  
   335  			if statedb.GetCodeSize(tx.Addr) == 0 {
   336  				panic(fmt.Errorf("Failed to create a contract%v", tx.Addr))
   337  			}
   338  
   339  			statedb.AddBalance(tx.Addr, val)
   340  		}
   341  
   342  		if debug {
   343  			vm.WriteTrace(os.Stderr, vmcfg.Tracer.(*vm.StructLogger).StructLogs())
   344  			vm.WriteLogs(os.Stderr, statedb.Logs())
   345  		}
   346  
   347  		statedb.SetBalance(systemFaucet, big.NewInt(0))
   348  		statedb.SetBalance(author, big.NewInt(0))
   349  		root = statedb.IntermediateRoot(false)
   350  		head.Root = root
   351  	}
   352  	//---
   353  
   354  	statedb.Commit(false)
   355  	statedb.Database().TrieDB().Commit(root, true)
   356  
   357  	return types.NewBlock(head, nil, nil, nil)
   358  }
   359  
   360  // Commit writes the block and state of a genesis specification to the database.
   361  // The block is committed as the canonical head block.
   362  func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
   363  	block := g.ToBlock(db)
   364  	if block.Number().Sign() != 0 {
   365  		return nil, fmt.Errorf("can't commit genesis block with number > 0")
   366  	}
   367  	rawdb.WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty)
   368  	rawdb.WriteBlock(db, block)
   369  	rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
   370  	rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
   371  	rawdb.WriteHeadBlockHash(db, block.Hash())
   372  	rawdb.WriteHeadHeaderHash(db, block.Hash())
   373  
   374  	config := g.Config
   375  	if config == nil {
   376  		config = params.AllEthashProtocolChanges
   377  	}
   378  	rawdb.WriteChainConfig(db, block.Hash(), config)
   379  	return block, nil
   380  }
   381  
   382  // MustCommit writes the genesis block and state to db, panicking on error.
   383  // The block is committed as the canonical head block.
   384  func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
   385  	block, err := g.Commit(db)
   386  	if err != nil {
   387  		panic(err)
   388  	}
   389  	return block
   390  }
   391  
   392  // GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
   393  func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
   394  	g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
   395  	return g.MustCommit(db)
   396  }
   397  
   398  // DefaultGenesisBlock returns the Ethereum main net genesis block.
   399  func DefaultGenesisBlock() *Genesis {
   400  	return &Genesis{
   401  		Config:     params.MainnetChainConfig,
   402  		Nonce:      66,
   403  		ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
   404  		GasLimit:   0,
   405  		Difficulty: big.NewInt(17179869184),
   406  		Alloc:      decodePrealloc(mainnetAllocData),
   407  	}
   408  }
   409  
   410  // DefaultTestnetGenesisBlock returns the Ropsten network genesis block.
   411  func DefaultTestnetGenesisBlock() *Genesis {
   412  	return &Genesis{
   413  		Config:     params.TestnetChainConfig,
   414  		Nonce:      66,
   415  		ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
   416  		GasLimit:   0,
   417  		Difficulty: big.NewInt(1048576),
   418  		Alloc:      decodePrealloc(testnetAllocData),
   419  	}
   420  }
   421  
   422  func DefaultEnergiMainnetGenesisBlock() *Genesis {
   423  	return &Genesis{
   424  		Config:     params.EnergiMainnetChainConfig,
   425  		Coinbase:   energi_params.Energi_Treasury,
   426  		Nonce:      0,
   427  		Timestamp:  1569888000000,
   428  		ExtraData:  []byte{},
   429  		GasLimit:   8000000,
   430  		Difficulty: big.NewInt(0xFFFF),
   431  		Alloc:      DefaultPrealloc(),
   432  		Xfers:      DeployEnergiGovernance(params.EnergiMainnetChainConfig),
   433  	}
   434  }
   435  
   436  func DefaultEnergiTestnetGenesisBlock() *Genesis {
   437  	// Gen2 e3d97b4c8ce67242fbbc857ee64b49f3ce32b02df81b45359d3cd0b03c7b53ee
   438  	// Time: 1561134790
   439  	// Number: 367350
   440  	return &Genesis{
   441  		Config:     params.EnergiTestnetChainConfig,
   442  		Coinbase:   energi_params.Energi_Treasury,
   443  		Timestamp:  1561134790,
   444  		Nonce:      0,
   445  		ExtraData:  []byte{},
   446  		GasLimit:   8000000,
   447  		Difficulty: big.NewInt(0xFFFF),
   448  		Alloc:      DefaultPrealloc(),
   449  		Xfers:      DeployEnergiGovernance(params.EnergiTestnetChainConfig),
   450  	}
   451  }
   452  
   453  // DeveloperEnergiGenesisBlock scans the custom genesis block from the provided
   454  // file path.
   455  func DeveloperEnergiGenesisBlock(customGenesisPath string) (*Genesis, error) {
   456  	file, err := os.Open(customGenesisPath)
   457  	defer file.Close()
   458  	if err != nil {
   459  		return nil, fmt.Errorf("Failed to read genesis file: %v", err)
   460  	}
   461  
   462  	genesis := new(Genesis)
   463  	if err := json.NewDecoder(file).Decode(genesis); err != nil {
   464  		return nil, fmt.Errorf("invalid genesis file: %v", err)
   465  	}
   466  	genesis.Xfers = append(genesis.Xfers, DeployEnergiGovernance(genesis.Config)...)
   467  	return genesis, nil
   468  }
   469  
   470  // DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must
   471  // be seeded with the
   472  func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
   473  	// Override the default period to the user requested one
   474  	config := *params.AllCliqueProtocolChanges
   475  	config.Clique.Period = period
   476  
   477  	// Assemble and return the genesis with the precompiles and faucet pre-funded
   478  	return &Genesis{
   479  		Config:     &config,
   480  		ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, 65)...),
   481  		GasLimit:   0,
   482  		Difficulty: big.NewInt(1),
   483  		Alloc: map[common.Address]GenesisAccount{
   484  			common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   485  			common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   486  			common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   487  			common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   488  			common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   489  			common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   490  			common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   491  			common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   492  			faucet:                           {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
   493  		},
   494  	}
   495  }
   496  
   497  func DefaultPrealloc() GenesisAlloc {
   498  	return GenesisAlloc{
   499  		common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
   500  		common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
   501  		common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
   502  		common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
   503  		common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
   504  		common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
   505  		common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
   506  		common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
   507  	}
   508  }
   509  
   510  func decodePrealloc(data string) GenesisAlloc {
   511  	if len(data) == 0 {
   512  		return DefaultPrealloc()
   513  	}
   514  
   515  	var p []struct{ Addr, Balance *big.Int }
   516  	if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
   517  		panic(err)
   518  	}
   519  	ga := make(GenesisAlloc, len(p))
   520  	for _, account := range p {
   521  		ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
   522  	}
   523  	return ga
   524  }
   525  
   526  //=====================================
   527  func deployEnergiContract(
   528  	xfers *GenesisXfers,
   529  	dst common.Address,
   530  	value *big.Int,
   531  	abi_json string, hex_code string,
   532  	params ...interface{},
   533  ) {
   534  	parsed_abi, err := abi.JSON(strings.NewReader(abi_json))
   535  	if err != nil {
   536  		panic(fmt.Errorf("invalid JSON: %v", err))
   537  	}
   538  
   539  	input, err := parsed_abi.Pack("", params...)
   540  	if err != nil {
   541  		panic(fmt.Errorf("invalid ABI: %v", err))
   542  	}
   543  
   544  	code := append(common.FromHex(hex_code), input...)
   545  	*xfers = append(*xfers, GenesisXfer{
   546  		Addr:  dst,
   547  		Code:  code,
   548  		Value: value,
   549  	})
   550  }
   551  
   552  func DeployEnergiGovernance(config *params.ChainConfig) GenesisXfers {
   553  	xfers := make(GenesisXfers, 0, 16)
   554  
   555  	if config == nil {
   556  		return xfers
   557  	}
   558  
   559  	//---
   560  	ver := 2
   561  
   562  	// Hardcoded Governance V1
   563  	deployEnergiContract(
   564  		&xfers,
   565  		energi_params.Energi_BlockRewardV1,
   566  		nil,
   567  		energi_abi.BlockRewardV1ABI,
   568  		energi_abi.BlockRewardV1Bin,
   569  		energi_params.Energi_BlockReward,
   570  		[4]common.Address{
   571  			energi_params.Energi_StakerReward,
   572  			energi_params.Energi_BackboneReward,
   573  			energi_params.Energi_Treasury,
   574  			energi_params.Energi_MasternodeRegistry,
   575  		},
   576  	)
   577  	deployEnergiContract(
   578  		&xfers,
   579  		energi_params.Energi_TreasuryV1,
   580  		nil,
   581  		energi_abi.TreasuryV1ABI,
   582  		energi_abi.TreasuryV1Bin,
   583  		energi_params.Energi_Treasury,
   584  		energi_params.Energi_MasternodeRegistry,
   585  		config.SuperblockCycle,
   586  	)
   587  	deployEnergiContract(
   588  		&xfers,
   589  		energi_params.Energi_StakerRewardV1,
   590  		nil,
   591  		energi_abi.StakerRewardV1ABI,
   592  		energi_abi.StakerRewardV1Bin,
   593  		energi_params.Energi_StakerReward,
   594  	)
   595  	deployEnergiContract(
   596  		&xfers,
   597  		energi_params.Energi_BackboneRewardV1,
   598  		nil,
   599  		energi_abi.BackboneRewardV1ABI,
   600  		energi_abi.BackboneRewardV1Bin,
   601  		energi_params.Energi_BackboneReward,
   602  		config.Energi.BackboneAddress,
   603  	)
   604  	if ver > 1 {
   605  		deployEnergiContract(
   606  			&xfers,
   607  			energi_params.Energi_SporkRegistryV1,
   608  			nil,
   609  			energi_abi.SporkRegistryV2ABI,
   610  			energi_abi.SporkRegistryV2Bin,
   611  			energi_params.Energi_SporkRegistry,
   612  			energi_params.Energi_MasternodeRegistry,
   613  			config.Energi.CPPSigner,
   614  		)
   615  		deployEnergiContract(
   616  			&xfers,
   617  			energi_params.Energi_CheckpointRegistryV1,
   618  			nil,
   619  			energi_abi.CheckpointRegistryV2ABI,
   620  			energi_abi.CheckpointRegistryV2Bin,
   621  			energi_params.Energi_CheckpointRegistry,
   622  			energi_params.Energi_MasternodeRegistry,
   623  			config.Energi.CPPSigner,
   624  		)
   625  		deployEnergiContract(
   626  			&xfers,
   627  			energi_params.Energi_MasternodeTokenV1,
   628  			nil,
   629  			energi_abi.MasternodeTokenV2ABI,
   630  			energi_abi.MasternodeTokenV2Bin,
   631  			energi_params.Energi_MasternodeToken,
   632  			energi_params.Energi_MasternodeRegistry,
   633  		)
   634  		deployEnergiContract(
   635  			&xfers,
   636  			energi_params.Energi_MasternodeRegistryV1,
   637  			nil,
   638  			energi_abi.MasternodeRegistryV2ABI,
   639  			energi_abi.MasternodeRegistryV2Bin,
   640  			energi_params.Energi_MasternodeRegistry,
   641  			energi_params.Energi_MasternodeToken,
   642  			energi_params.Energi_Treasury,
   643  			[5]*big.Int{
   644  				config.MNRequireValidation,
   645  				config.MNValidationPeriod,
   646  				config.MNCleanupPeriod,
   647  				config.MNEverCollateral,
   648  				config.MNRewardsPerBlock,
   649  			},
   650  		)
   651  	} else {
   652  		panic("Energi Genesis V1 is not supported anymore")
   653  	}
   654  	deployEnergiContract(
   655  		&xfers,
   656  		energi_params.Energi_BlacklistRegistryV1,
   657  		nil,
   658  		energi_abi.BlacklistRegistryV1ABI,
   659  		energi_abi.BlacklistRegistryV1Bin,
   660  		energi_params.Energi_BlacklistRegistry,
   661  		energi_params.Energi_MasternodeRegistry,
   662  		energi_params.Energi_MigrationContract,
   663  		energi_params.Energi_CompensationFundV1,
   664  		config.Energi.EBISigner,
   665  	)
   666  	deployEnergiContract(
   667  		&xfers,
   668  		energi_params.Energi_CompensationFundV1,
   669  		nil,
   670  		energi_abi.TreasuryV1ABI,
   671  		energi_abi.TreasuryV1Bin,
   672  		energi_params.Energi_BlacklistRegistryV1,
   673  		energi_params.Energi_MasternodeRegistry,
   674  		common.Big1, // unused
   675  	)
   676  	deployEnergiContract(
   677  		&xfers,
   678  		energi_params.Energi_MigrationContract,
   679  		new(big.Int).Mul(big.NewInt(0xFFFF), big.NewInt(1e18)),
   680  		energi_abi.Gen2MigrationABI,
   681  		energi_abi.Gen2MigrationBin,
   682  		energi_params.Energi_BlacklistRegistry,
   683  		config.ChainID,
   684  		config.Energi.MigrationSigner,
   685  	)
   686  	deployEnergiContract(
   687  		&xfers,
   688  		energi_params.Energi_Blacklist,
   689  		nil,
   690  		energi_abi.DummyAccountABI,
   691  		energi_abi.DummyAccountBin,
   692  	)
   693  	deployEnergiContract(
   694  		&xfers,
   695  		energi_params.Energi_Whitelist,
   696  		nil,
   697  		energi_abi.DummyAccountABI,
   698  		energi_abi.DummyAccountBin,
   699  	)
   700  	deployEnergiContract(
   701  		&xfers,
   702  		energi_params.Energi_MasternodeList,
   703  		nil,
   704  		energi_abi.DummyAccountABI,
   705  		energi_abi.DummyAccountBin,
   706  	)
   707  
   708  	// Proxy List
   709  	proxies := map[common.Address]common.Address{
   710  		energi_params.Energi_BlockReward:        energi_params.Energi_BlockRewardV1,
   711  		energi_params.Energi_Treasury:           energi_params.Energi_TreasuryV1,
   712  		energi_params.Energi_MasternodeRegistry: energi_params.Energi_MasternodeRegistryV1,
   713  		energi_params.Energi_StakerReward:       energi_params.Energi_StakerRewardV1,
   714  		energi_params.Energi_BackboneReward:     energi_params.Energi_BackboneRewardV1,
   715  		energi_params.Energi_SporkRegistry:      energi_params.Energi_SporkRegistryV1,
   716  		energi_params.Energi_CheckpointRegistry: energi_params.Energi_CheckpointRegistryV1,
   717  		energi_params.Energi_BlacklistRegistry:  energi_params.Energi_BlacklistRegistryV1,
   718  		energi_params.Energi_MasternodeToken:    energi_params.Energi_MasternodeTokenV1,
   719  	}
   720  	for k, v := range proxies {
   721  		deployEnergiContract(
   722  			&xfers,
   723  			k,
   724  			nil,
   725  			energi_abi.GovernedProxyABI,
   726  			energi_abi.GovernedProxyBin,
   727  			v,
   728  			energi_params.Energi_SporkRegistry,
   729  		)
   730  	}
   731  
   732  	return xfers
   733  }