github.com/klaytn/klaytn@v1.12.1/params/config.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from params/config.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package params
    22  
    23  import (
    24  	"encoding/json"
    25  	"fmt"
    26  	"math/big"
    27  
    28  	"github.com/klaytn/klaytn/common"
    29  	"github.com/klaytn/klaytn/log"
    30  )
    31  
    32  // Genesis hashes to enforce below configs on.
    33  var (
    34  	CypressGenesisHash      = common.HexToHash("0xc72e5293c3c3ba38ed8ae910f780e4caaa9fb95e79784f7ab74c3c262ea7137e") // cypress genesis hash to enforce below configs on
    35  	BaobabGenesisHash       = common.HexToHash("0xe33ff05ceec2581ca9496f38a2bf9baad5d4eed629e896ccb33d1dc991bc4b4a") // baobab genesis hash to enforce below configs on
    36  	AuthorAddressForTesting = common.HexToAddress("0xc0ea08a2d404d3172d2add29a45be56da40e2949")
    37  	mintingAmount, _        = new(big.Int).SetString("9600000000000000000", 10)
    38  	logger                  = log.NewModuleLogger(log.Governance)
    39  )
    40  
    41  var (
    42  	// CypressChainConfig is the chain parameters to run a node on the cypress main network.
    43  	CypressChainConfig = &ChainConfig{
    44  		ChainID:                  big.NewInt(int64(CypressNetworkId)),
    45  		IstanbulCompatibleBlock:  big.NewInt(86816005),
    46  		LondonCompatibleBlock:    big.NewInt(86816005),
    47  		EthTxTypeCompatibleBlock: big.NewInt(86816005),
    48  		MagmaCompatibleBlock:     big.NewInt(99841497),
    49  		KoreCompatibleBlock:      big.NewInt(119750400),
    50  		ShanghaiCompatibleBlock:  big.NewInt(135456000),
    51  		CancunCompatibleBlock:    big.NewInt(147534000),
    52  		RandaoCompatibleBlock:    big.NewInt(147534000),
    53  		RandaoRegistry: &RegistryConfig{
    54  			Records: map[string]common.Address{
    55  				"KIP113": common.HexToAddress("0x3e80e75975bdb8e04B800485DD28BebeC6d97679"),
    56  			},
    57  			Owner: common.HexToAddress("0x04992a2B7E7CE809d409adE32185D49A96AAa32d"),
    58  		},
    59  		Kip103CompatibleBlock: big.NewInt(119750400),
    60  		Kip103ContractAddress: common.HexToAddress("0xD5ad6D61Dd87EdabE2332607C328f5cc96aeCB95"),
    61  		DeriveShaImpl:         2,
    62  		Governance: &GovernanceConfig{
    63  			GoverningNode:  common.HexToAddress("0x52d41ca72af615a1ac3301b0a93efa222ecc7541"),
    64  			GovernanceMode: "single",
    65  			Reward: &RewardConfig{
    66  				MintingAmount:          mintingAmount,
    67  				Ratio:                  "34/54/12",
    68  				UseGiniCoeff:           true,
    69  				DeferredTxFee:          true,
    70  				StakingUpdateInterval:  86400,
    71  				ProposerUpdateInterval: 3600,
    72  				MinimumStake:           big.NewInt(5000000),
    73  			},
    74  		},
    75  		Istanbul: &IstanbulConfig{
    76  			Epoch:          604800,
    77  			ProposerPolicy: 2,
    78  			SubGroupSize:   22,
    79  		},
    80  		UnitPrice: 25000000000,
    81  	}
    82  
    83  	// BaobabChainConfig contains the chain parameters to run a node on the Baobab test network.
    84  	BaobabChainConfig = &ChainConfig{
    85  		ChainID:                  big.NewInt(int64(BaobabNetworkId)),
    86  		IstanbulCompatibleBlock:  big.NewInt(75373312),
    87  		LondonCompatibleBlock:    big.NewInt(80295291),
    88  		EthTxTypeCompatibleBlock: big.NewInt(86513895),
    89  		MagmaCompatibleBlock:     big.NewInt(98347376),
    90  		KoreCompatibleBlock:      big.NewInt(111736800),
    91  		ShanghaiCompatibleBlock:  big.NewInt(131608000),
    92  		CancunCompatibleBlock:    big.NewInt(141367000),
    93  		RandaoCompatibleBlock:    big.NewInt(141367000),
    94  		RandaoRegistry: &RegistryConfig{
    95  			Records: map[string]common.Address{
    96  				"KIP113": common.HexToAddress("0x4BEed0651C46aE5a7CB3b7737345d2ee733789e6"),
    97  			},
    98  			Owner: common.HexToAddress("0x04992a2B7E7CE809d409adE32185D49A96AAa32d"),
    99  		},
   100  		Kip103CompatibleBlock: big.NewInt(119145600),
   101  		Kip103ContractAddress: common.HexToAddress("0xD5ad6D61Dd87EdabE2332607C328f5cc96aeCB95"),
   102  		DeriveShaImpl:         2,
   103  		Governance: &GovernanceConfig{
   104  			GoverningNode:  common.HexToAddress("0x99fb17d324fa0e07f23b49d09028ac0919414db6"),
   105  			GovernanceMode: "single",
   106  			Reward: &RewardConfig{
   107  				MintingAmount:          mintingAmount,
   108  				Ratio:                  "34/54/12",
   109  				UseGiniCoeff:           true,
   110  				DeferredTxFee:          true,
   111  				StakingUpdateInterval:  86400,
   112  				ProposerUpdateInterval: 3600,
   113  				MinimumStake:           big.NewInt(5000000),
   114  			},
   115  		},
   116  		Istanbul: &IstanbulConfig{
   117  			Epoch:          604800,
   118  			ProposerPolicy: 2,
   119  			SubGroupSize:   22,
   120  		},
   121  		UnitPrice: 25000000000,
   122  	}
   123  
   124  	// AllGxhashProtocolChanges contains every protocol change (GxIPs) introduced
   125  	// and accepted by the klaytn developers into the Klaytn consensus.
   126  	//
   127  	// This configuration is intentionally not using keyed fields to force anyone
   128  	// adding flags to the config to also have to set these fields.
   129  	AllGxhashProtocolChanges = &ChainConfig{
   130  		ChainID:  big.NewInt(0),
   131  		Gxhash:   new(GxhashConfig),
   132  		Clique:   nil,
   133  		Istanbul: nil,
   134  	}
   135  
   136  	// AllCliqueProtocolChanges contains every protocol change (GxIPs) introduced
   137  	// and accepted by the klaytn developers into the Clique consensus.
   138  	//
   139  	// This configuration is intentionally not using keyed fields to force anyone
   140  	// adding flags to the config to also have to set these fields.
   141  	AllCliqueProtocolChanges = &ChainConfig{
   142  		ChainID:  big.NewInt(0),
   143  		Gxhash:   nil,
   144  		Clique:   &CliqueConfig{Period: 0, Epoch: 30000},
   145  		Istanbul: nil,
   146  	}
   147  
   148  	TestChainConfig = &ChainConfig{
   149  		ChainID:       big.NewInt(1),
   150  		Gxhash:        new(GxhashConfig),
   151  		Clique:        nil,
   152  		Istanbul:      nil,
   153  		UnitPrice:     1, // NOTE-Klaytn Use UnitPrice 1 for tests
   154  		DeriveShaImpl: 0,
   155  	}
   156  	TestRules = TestChainConfig.Rules(new(big.Int))
   157  
   158  	// istanbul BFT
   159  	BFTTestChainConfig = &ChainConfig{
   160  		ChainID:  big.NewInt(1),
   161  		Gxhash:   new(GxhashConfig),
   162  		Clique:   nil,
   163  		Istanbul: nil,
   164  	}
   165  )
   166  
   167  // VMLogTarget sets the output target of vmlog.
   168  // The values below can be OR'ed.
   169  //   - 0x0: no output (default)
   170  //   - 0x1: file (DATADIR/logs/vm.log)
   171  //   - 0x2: stdout (like logger.DEBUG)
   172  var VMLogTarget = 0x0
   173  
   174  const (
   175  	VMLogToFile   = 0x1
   176  	VMLogToStdout = 0x2
   177  	VMLogToAll    = VMLogToFile | VMLogToStdout
   178  
   179  	UpperGasLimit = uint64(999999999999)
   180  )
   181  
   182  const (
   183  	PasswordLength = 16
   184  )
   185  
   186  // ChainConfig is the blockchain config which determines the blockchain settings.
   187  //
   188  // ChainConfig is stored in the database on a per block basis. This means
   189  // that any network, identified by its genesis block, can have its own
   190  // set of configuration options.
   191  type ChainConfig struct {
   192  	ChainID *big.Int `json:"chainId"` // chainId identifies the current chain and is used for replay protection
   193  
   194  	// "Compatible" means that it is EVM compatible(the opcode and precompiled contracts are the same as Ethereum EVM).
   195  	// In other words, not all the hard fork items are included.
   196  	IstanbulCompatibleBlock  *big.Int `json:"istanbulCompatibleBlock,omitempty"`  // IstanbulCompatibleBlock switch block (nil = no fork, 0 = already on istanbul)
   197  	LondonCompatibleBlock    *big.Int `json:"londonCompatibleBlock,omitempty"`    // LondonCompatibleBlock switch block (nil = no fork, 0 = already on london)
   198  	EthTxTypeCompatibleBlock *big.Int `json:"ethTxTypeCompatibleBlock,omitempty"` // EthTxTypeCompatibleBlock switch block (nil = no fork, 0 = already on ethTxType)
   199  	MagmaCompatibleBlock     *big.Int `json:"magmaCompatibleBlock,omitempty"`     // MagmaCompatible switch block (nil = no fork, 0 already on Magma)
   200  	KoreCompatibleBlock      *big.Int `json:"koreCompatibleBlock,omitempty"`      // KoreCompatible switch block (nil = no fork, 0 already on Kore)
   201  	ShanghaiCompatibleBlock  *big.Int `json:"shanghaiCompatibleBlock,omitempty"`  // ShanghaiCompatible switch block (nil = no fork, 0 already on shanghai)
   202  	CancunCompatibleBlock    *big.Int `json:"cancunCompatibleBlock,omitempty"`    // CancunCompatible switch block (nil = no fork, 0 already on Cancun)
   203  
   204  	// KIP103 is a special purpose hardfork feature that can be executed only once
   205  	// Both Kip103CompatibleBlock and Kip103ContractAddress should be specified to enable KIP103
   206  	Kip103CompatibleBlock *big.Int       `json:"kip103CompatibleBlock,omitempty"` // Kip103Compatible activate block (nil = no fork)
   207  	Kip103ContractAddress common.Address `json:"kip103ContractAddress,omitempty"` // Kip103 contract address already deployed on the network
   208  
   209  	// Randao is an optional hardfork
   210  	// RandaoCompatibleBlock, RandaoRegistryRecords and RandaoRegistryOwner all must be specified to enable Randao
   211  	RandaoCompatibleBlock *big.Int        `json:"randaoCompatibleBlock,omitempty"` // RandaoCompatible activate block (nil = no fork)
   212  	RandaoRegistry        *RegistryConfig `json:"randaoRegistry,omitempty"`        // Registry initial states
   213  
   214  	// Various consensus engines
   215  	Gxhash   *GxhashConfig   `json:"gxhash,omitempty"` // (deprecated) not supported engine
   216  	Clique   *CliqueConfig   `json:"clique,omitempty"`
   217  	Istanbul *IstanbulConfig `json:"istanbul,omitempty"`
   218  
   219  	UnitPrice     uint64            `json:"unitPrice"`
   220  	DeriveShaImpl int               `json:"deriveShaImpl"`
   221  	Governance    *GovernanceConfig `json:"governance"`
   222  }
   223  
   224  // GovernanceConfig stores governance information for a network
   225  type GovernanceConfig struct {
   226  	GoverningNode    common.Address `json:"governingNode"`
   227  	GovernanceMode   string         `json:"governanceMode"`
   228  	GovParamContract common.Address `json:"govParamContract"`
   229  	Reward           *RewardConfig  `json:"reward,omitempty"`
   230  	KIP71            *KIP71Config   `json:"kip71,omitempty"`
   231  }
   232  
   233  func (g *GovernanceConfig) DeferredTxFee() bool {
   234  	return g.Reward.DeferredTxFee
   235  }
   236  
   237  // RewardConfig stores information about the network's token economy
   238  type RewardConfig struct {
   239  	MintingAmount          *big.Int `json:"mintingAmount"`
   240  	Ratio                  string   `json:"ratio"`                  // Define how much portion of reward be distributed to CN/KFF/KCF
   241  	Kip82Ratio             string   `json:"kip82ratio,omitempty"`   // Define how much portion of reward be distributed to proposer/stakers
   242  	UseGiniCoeff           bool     `json:"useGiniCoeff"`           // Decide if Gini Coefficient will be used or not
   243  	DeferredTxFee          bool     `json:"deferredTxFee"`          // Decide if TX fee will be handled instantly or handled later at block finalization
   244  	StakingUpdateInterval  uint64   `json:"stakingUpdateInterval"`  // Interval when staking information is updated
   245  	ProposerUpdateInterval uint64   `json:"proposerUpdateInterval"` // Interval when proposer information is updated
   246  	MinimumStake           *big.Int `json:"minimumStake"`           // Minimum amount of peb to join CCO
   247  }
   248  
   249  // Magma governance parameters
   250  type KIP71Config struct {
   251  	LowerBoundBaseFee         uint64 `json:"lowerboundbasefee"`         // Minimum base fee for dynamic gas price
   252  	UpperBoundBaseFee         uint64 `json:"upperboundbasefee"`         // Maximum base fee for dynamic gas price
   253  	GasTarget                 uint64 `json:"gastarget"`                 // Gauge parameter increasing or decreasing gas price
   254  	MaxBlockGasUsedForBaseFee uint64 `json:"maxblockgasusedforbasefee"` // Maximum network and process capacity to allow in a block
   255  	BaseFeeDenominator        uint64 `json:"basefeedenominator"`        // For normalizing effect of the rapid change like impulse gas used
   256  }
   257  
   258  // IstanbulConfig is the consensus engine configs for Istanbul based sealing.
   259  type IstanbulConfig struct {
   260  	Epoch          uint64 `json:"epoch"`  // Epoch length to reset votes and checkpoint
   261  	ProposerPolicy uint64 `json:"policy"` // The policy for proposer selection; 0: Round Robin, 1: Sticky, 2: Weighted Random
   262  	SubGroupSize   uint64 `json:"sub"`
   263  }
   264  
   265  // RegistryConfig is the initial KIP-149 system contract registry states.
   266  // It is installed at block (RandaoCompatibleBlock - 1). Initial states are not applied if RandaoCompatibleBlock is nil or 0.
   267  // To install the initial states from the block 0, use the AllocRegistry to generate GenesisAlloc.
   268  //
   269  // This struct only represents a special case of Registry state where:
   270  // - there is only one record for each name
   271  // - the activation of all records is zero
   272  // - the names array is lexicographically sorted
   273  type RegistryConfig struct {
   274  	Records map[string]common.Address `json:"records"`
   275  	Owner   common.Address            `json:"owner"`
   276  }
   277  
   278  // GxhashConfig is the consensus engine configs for proof-of-work based sealing.
   279  // Deprecated: Use IstanbulConfig or CliqueConfig.
   280  type GxhashConfig struct{}
   281  
   282  // String implements the stringer interface, returning the consensus engine details.
   283  func (c *GxhashConfig) String() string {
   284  	return "gxhash"
   285  }
   286  
   287  // CliqueConfig is the consensus engine configs for proof-of-authority based sealing.
   288  type CliqueConfig struct {
   289  	Period uint64 `json:"period"` // Number of seconds between blocks to enforce
   290  	Epoch  uint64 `json:"epoch"`  // Epoch length to reset votes and checkpoint
   291  }
   292  
   293  // String implements the stringer interface, returning the consensus engine details.
   294  func (c *CliqueConfig) String() string {
   295  	return "clique"
   296  }
   297  
   298  // String implements the stringer interface, returning the consensus engine details.
   299  func (c *IstanbulConfig) String() string {
   300  	return "istanbul"
   301  }
   302  
   303  // String implements the fmt.Stringer interface.
   304  func (c *ChainConfig) String() string {
   305  	var engine interface{}
   306  	switch {
   307  	case c.Gxhash != nil:
   308  		engine = c.Gxhash
   309  	case c.Clique != nil:
   310  		engine = c.Clique
   311  	case c.Istanbul != nil:
   312  		engine = c.Istanbul
   313  	default:
   314  		engine = "unknown"
   315  	}
   316  
   317  	kip103 := fmt.Sprintf("KIP103CompatibleBlock: %v KIP103ContractAddress %s", c.Kip103CompatibleBlock, c.Kip103ContractAddress.String())
   318  
   319  	if c.Istanbul != nil {
   320  		return fmt.Sprintf("{ChainID: %v IstanbulCompatibleBlock: %v LondonCompatibleBlock: %v EthTxTypeCompatibleBlock: %v MagmaCompatibleBlock: %v KoreCompatibleBlock: %v ShanghaiCompatibleBlock: %v CancunCompatibleBlock: %v RandaoCompatibleBlock: %v %s SubGroupSize: %d UnitPrice: %d DeriveShaImpl: %d Engine: %v}",
   321  			c.ChainID,
   322  			c.IstanbulCompatibleBlock,
   323  			c.LondonCompatibleBlock,
   324  			c.EthTxTypeCompatibleBlock,
   325  			c.MagmaCompatibleBlock,
   326  			c.KoreCompatibleBlock,
   327  			c.ShanghaiCompatibleBlock,
   328  			c.CancunCompatibleBlock,
   329  			c.RandaoCompatibleBlock,
   330  			kip103,
   331  			c.Istanbul.SubGroupSize,
   332  			c.UnitPrice,
   333  			c.DeriveShaImpl,
   334  			engine,
   335  		)
   336  	} else {
   337  		return fmt.Sprintf("{ChainID: %v IstanbulCompatibleBlock: %v LondonCompatibleBlock: %v EthTxTypeCompatibleBlock: %v MagmaCompatibleBlock: %v KoreCompatibleBlock: %v ShanghaiCompatibleBlock: %v CancunCompatibleBlock: %v RandaoCompatibleBlock: %v %s UnitPrice: %d DeriveShaImpl: %d Engine: %v }",
   338  			c.ChainID,
   339  			c.IstanbulCompatibleBlock,
   340  			c.LondonCompatibleBlock,
   341  			c.EthTxTypeCompatibleBlock,
   342  			c.MagmaCompatibleBlock,
   343  			c.KoreCompatibleBlock,
   344  			c.ShanghaiCompatibleBlock,
   345  			c.CancunCompatibleBlock,
   346  			c.RandaoCompatibleBlock,
   347  			kip103,
   348  			c.UnitPrice,
   349  			c.DeriveShaImpl,
   350  			engine,
   351  		)
   352  	}
   353  }
   354  
   355  func (c *ChainConfig) Copy() *ChainConfig {
   356  	r := &ChainConfig{}
   357  	j, _ := json.Marshal(c)
   358  	json.Unmarshal(j, r)
   359  	return r
   360  }
   361  
   362  // IsIstanbulForkEnabled returns whether num is either equal to the istanbul block or greater.
   363  func (c *ChainConfig) IsIstanbulForkEnabled(num *big.Int) bool {
   364  	return isForked(c.IstanbulCompatibleBlock, num)
   365  }
   366  
   367  // IsLondonForkEnabled returns whether num is either equal to the london block or greater.
   368  func (c *ChainConfig) IsLondonForkEnabled(num *big.Int) bool {
   369  	return isForked(c.LondonCompatibleBlock, num)
   370  }
   371  
   372  // IsEthTxTypeForkEnabled returns whether num is either equal to the ethTxType block or greater.
   373  func (c *ChainConfig) IsEthTxTypeForkEnabled(num *big.Int) bool {
   374  	return isForked(c.EthTxTypeCompatibleBlock, num)
   375  }
   376  
   377  // IsMagmaForkEnabled returns whether num is either equal to the magma block or greater.
   378  func (c *ChainConfig) IsMagmaForkEnabled(num *big.Int) bool {
   379  	return isForked(c.MagmaCompatibleBlock, num)
   380  }
   381  
   382  // IsKoreForkEnabled returns whether num is either equal to the kore block or greater.
   383  func (c *ChainConfig) IsKoreForkEnabled(num *big.Int) bool {
   384  	return isForked(c.KoreCompatibleBlock, num)
   385  }
   386  
   387  // IsShanghaiForkEnabled returns whether num is either equal to the shanghai block or greater.
   388  func (c *ChainConfig) IsShanghaiForkEnabled(num *big.Int) bool {
   389  	return isForked(c.ShanghaiCompatibleBlock, num)
   390  }
   391  
   392  // IsCancunForkEnabled returns whether num is either equal to the cancun block or greater.
   393  func (c *ChainConfig) IsCancunForkEnabled(num *big.Int) bool {
   394  	return isForked(c.CancunCompatibleBlock, num)
   395  }
   396  
   397  // IsRandaoForkEnabled returns whether num is either equal to the randao block or greater.
   398  func (c *ChainConfig) IsRandaoForkEnabled(num *big.Int) bool {
   399  	return isForked(c.RandaoCompatibleBlock, num)
   400  }
   401  
   402  // IsKIP103ForkBlock returns whether num is equal to the kip103 block.
   403  func (c *ChainConfig) IsKIP103ForkBlock(num *big.Int) bool {
   404  	if c.Kip103CompatibleBlock == nil || num == nil {
   405  		return false
   406  	}
   407  	return c.Kip103CompatibleBlock.Cmp(num) == 0
   408  }
   409  
   410  // IsRandaoForkBlockParent returns whethere num is one block before the randao block.
   411  func (c *ChainConfig) IsRandaoForkBlockParent(num *big.Int) bool {
   412  	if c.RandaoCompatibleBlock == nil || num == nil {
   413  		return false
   414  	}
   415  	nextNum := new(big.Int).Add(num, common.Big1)
   416  	return c.RandaoCompatibleBlock.Cmp(nextNum) == 0 // randao == num + 1
   417  }
   418  
   419  // IsRandaoForkBlock returns whether num is equal to the randao block.
   420  func (c *ChainConfig) IsRandaoForkBlock(num *big.Int) bool {
   421  	if c.RandaoCompatibleBlock == nil || num == nil {
   422  		return false
   423  	}
   424  	return c.RandaoCompatibleBlock.Cmp(num) == 0
   425  }
   426  
   427  // CheckCompatible checks whether scheduled fork transitions have been imported
   428  // with a mismatching chain configuration.
   429  func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64) *ConfigCompatError {
   430  	bhead := new(big.Int).SetUint64(height)
   431  
   432  	// Iterate checkCompatible to find the lowest conflict.
   433  	var lasterr *ConfigCompatError
   434  	for {
   435  		err := c.checkCompatible(newcfg, bhead)
   436  		if err == nil || (lasterr != nil && err.RewindTo == lasterr.RewindTo) {
   437  			break
   438  		}
   439  		lasterr = err
   440  		bhead.SetUint64(err.RewindTo)
   441  	}
   442  	return lasterr
   443  }
   444  
   445  // CheckConfigForkOrder checks that we don't "skip" any forks, geth isn't pluggable enough
   446  // to guarantee that forks can be implemented in a different order than on official networks
   447  func (c *ChainConfig) CheckConfigForkOrder() error {
   448  	type fork struct {
   449  		name     string
   450  		block    *big.Int
   451  		optional bool // if true, the fork may be nil and next fork is still allowed
   452  	}
   453  	var lastFork fork
   454  	for _, cur := range []fork{
   455  		{name: "istanbulBlock", block: c.IstanbulCompatibleBlock},
   456  		{name: "londonBlock", block: c.LondonCompatibleBlock},
   457  		{name: "ethTxTypeBlock", block: c.EthTxTypeCompatibleBlock},
   458  		{name: "magmaBlock", block: c.MagmaCompatibleBlock},
   459  		{name: "koreBlock", block: c.KoreCompatibleBlock},
   460  		{name: "shanghaiBlock", block: c.ShanghaiCompatibleBlock},
   461  		{name: "cancunBlock", block: c.CancunCompatibleBlock},
   462  		{name: "randaoBlock", block: c.RandaoCompatibleBlock, optional: true},
   463  	} {
   464  		if lastFork.name != "" {
   465  			// Next one must be higher number
   466  			if lastFork.block == nil && cur.block != nil {
   467  				return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at %v",
   468  					lastFork.name, cur.name, cur.block)
   469  			}
   470  			if lastFork.block != nil && cur.block != nil {
   471  				if lastFork.block.Cmp(cur.block) > 0 {
   472  					return fmt.Errorf("unsupported fork ordering: %v enabled at %v, but %v enabled at %v",
   473  						lastFork.name, lastFork.block, cur.name, cur.block)
   474  				}
   475  			}
   476  		}
   477  		// If it was optional and not set, then ignore it
   478  		if !cur.optional || cur.block != nil {
   479  			lastFork = cur
   480  		}
   481  	}
   482  	return nil
   483  }
   484  
   485  func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, head *big.Int) *ConfigCompatError {
   486  	if isForkIncompatible(c.IstanbulCompatibleBlock, newcfg.IstanbulCompatibleBlock, head) {
   487  		return newCompatError("Istanbul Block", c.IstanbulCompatibleBlock, newcfg.IstanbulCompatibleBlock)
   488  	}
   489  	if isForkIncompatible(c.LondonCompatibleBlock, newcfg.LondonCompatibleBlock, head) {
   490  		return newCompatError("London Block", c.LondonCompatibleBlock, newcfg.LondonCompatibleBlock)
   491  	}
   492  	if isForkIncompatible(c.EthTxTypeCompatibleBlock, newcfg.EthTxTypeCompatibleBlock, head) {
   493  		return newCompatError("EthTxType Block", c.EthTxTypeCompatibleBlock, newcfg.EthTxTypeCompatibleBlock)
   494  	}
   495  	if isForkIncompatible(c.MagmaCompatibleBlock, newcfg.MagmaCompatibleBlock, head) {
   496  		return newCompatError("Magma Block", c.MagmaCompatibleBlock, newcfg.MagmaCompatibleBlock)
   497  	}
   498  	if isForkIncompatible(c.KoreCompatibleBlock, newcfg.KoreCompatibleBlock, head) {
   499  		return newCompatError("Kore Block", c.KoreCompatibleBlock, newcfg.KoreCompatibleBlock)
   500  	}
   501  	// We have intentionally skipped kip103Block in the fork ordering check since kip103 is designed
   502  	// as an optional hardfork and there are no dependency with other forks.
   503  	if isForkIncompatible(c.ShanghaiCompatibleBlock, newcfg.ShanghaiCompatibleBlock, head) {
   504  		return newCompatError("Shanghai Block", c.ShanghaiCompatibleBlock, newcfg.ShanghaiCompatibleBlock)
   505  	}
   506  	if isForkIncompatible(c.CancunCompatibleBlock, newcfg.CancunCompatibleBlock, head) {
   507  		return newCompatError("Cancun Block", c.CancunCompatibleBlock, newcfg.CancunCompatibleBlock)
   508  	}
   509  	if isForkIncompatible(c.RandaoCompatibleBlock, newcfg.RandaoCompatibleBlock, head) {
   510  		return newCompatError("Randao Block", c.RandaoCompatibleBlock, newcfg.RandaoCompatibleBlock)
   511  	}
   512  	return nil
   513  }
   514  
   515  // SetDefaultsForGenesis fills undefined chain config with default values.
   516  // Only used for generating genesis.
   517  // Empty values from genesis.json will be left out from genesis.
   518  func (c *ChainConfig) SetDefaultsForGenesis() {
   519  	if c.Clique == nil && c.Istanbul == nil {
   520  		c.Istanbul = GetDefaultIstanbulConfig()
   521  		logger.Warn("Override the default Istanbul config to the chain config")
   522  	}
   523  
   524  	if c.Governance == nil {
   525  		c.Governance = GetDefaultGovernanceConfigForGenesis()
   526  		logger.Warn("Override the default governance config to the chain config")
   527  	}
   528  
   529  	if c.Governance.Reward == nil {
   530  		c.Governance.Reward = GetDefaultRewardConfigForGenesis()
   531  		logger.Warn("Override the default governance reward config to the chain config", "reward",
   532  			c.Governance.Reward)
   533  	}
   534  
   535  	// StakingUpdateInterval must be nonzero because it is used as denominator
   536  	if c.Governance.Reward.StakingUpdateInterval == 0 {
   537  		c.Governance.Reward.StakingUpdateInterval = StakingUpdateInterval()
   538  		logger.Warn("Override the default staking update interval to the chain config", "interval",
   539  			c.Governance.Reward.StakingUpdateInterval)
   540  	}
   541  
   542  	// ProposerUpdateInterval must be nonzero because it is used as denominator
   543  	if c.Governance.Reward.ProposerUpdateInterval == 0 {
   544  		c.Governance.Reward.ProposerUpdateInterval = ProposerUpdateInterval()
   545  		logger.Warn("Override the default proposer update interval to the chain config", "interval",
   546  			c.Governance.Reward.ProposerUpdateInterval)
   547  	}
   548  }
   549  
   550  // SetDefaults fills undefined chain config with default values
   551  // so that nil pointer does not exist in the chain config
   552  func (c *ChainConfig) SetDefaults() {
   553  	c.SetDefaultsForGenesis()
   554  
   555  	if c.Governance.KIP71 == nil {
   556  		c.Governance.KIP71 = GetDefaultKIP71Config()
   557  	}
   558  	if c.Governance.Reward.Kip82Ratio == "" {
   559  		c.Governance.Reward.Kip82Ratio = DefaultKip82Ratio
   560  	}
   561  }
   562  
   563  // isForkIncompatible returns true if a fork scheduled at s1 cannot be rescheduled to
   564  // block s2 because head is already past the fork.
   565  func isForkIncompatible(s1, s2, head *big.Int) bool {
   566  	return (isForked(s1, head) || isForked(s2, head)) && !configNumEqual(s1, s2)
   567  }
   568  
   569  // isForked returns whether a fork scheduled at block s is active at the given head block.
   570  func isForked(s, head *big.Int) bool {
   571  	if s == nil || head == nil {
   572  		return false
   573  	}
   574  	return s.Cmp(head) <= 0
   575  }
   576  
   577  func configNumEqual(x, y *big.Int) bool {
   578  	if x == nil {
   579  		return y == nil
   580  	}
   581  	if y == nil {
   582  		return x == nil
   583  	}
   584  	return x.Cmp(y) == 0
   585  }
   586  
   587  // ConfigCompatError is raised if the locally-stored blockchain is initialised with a
   588  // ChainConfig that would alter the past.
   589  type ConfigCompatError struct {
   590  	What string
   591  	// block numbers of the stored and new configurations
   592  	StoredConfig, NewConfig *big.Int
   593  	// the block number to which the local chain must be rewound to correct the error
   594  	RewindTo uint64
   595  }
   596  
   597  func newCompatError(what string, storedblock, newblock *big.Int) *ConfigCompatError {
   598  	var rew *big.Int
   599  	switch {
   600  	case storedblock == nil:
   601  		rew = newblock
   602  	case newblock == nil || storedblock.Cmp(newblock) < 0:
   603  		rew = storedblock
   604  	default:
   605  		rew = newblock
   606  	}
   607  	err := &ConfigCompatError{what, storedblock, newblock, 0}
   608  	if rew != nil && rew.Sign() > 0 {
   609  		err.RewindTo = rew.Uint64() - 1
   610  	}
   611  	return err
   612  }
   613  
   614  func (err *ConfigCompatError) Error() string {
   615  	return fmt.Sprintf("mismatching %s in database (have %d, want %d, rewindto %d)", err.What, err.StoredConfig, err.NewConfig, err.RewindTo)
   616  }
   617  
   618  // Rules wraps ChainConfig and is merely syntactic sugar or can be used for functions
   619  // that do not have or require information about the block.
   620  //
   621  // Rules is a one time interface meaning that it shouldn't be used in between transition
   622  // phases.
   623  type Rules struct {
   624  	ChainID     *big.Int
   625  	IsIstanbul  bool
   626  	IsLondon    bool
   627  	IsEthTxType bool
   628  	IsMagma     bool
   629  	IsKore      bool
   630  	IsShanghai  bool
   631  	IsCancun    bool
   632  	IsRandao    bool
   633  }
   634  
   635  // Rules ensures c's ChainID is not nil.
   636  func (c *ChainConfig) Rules(num *big.Int) Rules {
   637  	chainID := c.ChainID
   638  	if chainID == nil {
   639  		chainID = new(big.Int)
   640  	}
   641  	return Rules{
   642  		ChainID:     new(big.Int).Set(chainID),
   643  		IsIstanbul:  c.IsIstanbulForkEnabled(num),
   644  		IsLondon:    c.IsLondonForkEnabled(num),
   645  		IsEthTxType: c.IsEthTxTypeForkEnabled(num),
   646  		IsMagma:     c.IsMagmaForkEnabled(num),
   647  		IsKore:      c.IsKoreForkEnabled(num),
   648  		IsShanghai:  c.IsShanghaiForkEnabled(num),
   649  		IsCancun:    c.IsCancunForkEnabled(num),
   650  		IsRandao:    c.IsRandaoForkEnabled(num),
   651  	}
   652  }
   653  
   654  // cypress genesis config
   655  func GetDefaultGovernanceConfigForGenesis() *GovernanceConfig {
   656  	gov := &GovernanceConfig{
   657  		GovernanceMode: DefaultGovernanceMode,
   658  		GoverningNode:  common.HexToAddress(DefaultGoverningNode),
   659  		Reward:         GetDefaultRewardConfigForGenesis(),
   660  	}
   661  	return gov
   662  }
   663  
   664  func GetDefaultGovernanceConfig() *GovernanceConfig {
   665  	gov := &GovernanceConfig{
   666  		GovernanceMode:   DefaultGovernanceMode,
   667  		GoverningNode:    common.HexToAddress(DefaultGoverningNode),
   668  		GovParamContract: common.HexToAddress(DefaultGovParamContract),
   669  		Reward:           GetDefaultRewardConfig(),
   670  		KIP71:            GetDefaultKIP71Config(),
   671  	}
   672  	return gov
   673  }
   674  
   675  func GetDefaultIstanbulConfig() *IstanbulConfig {
   676  	return &IstanbulConfig{
   677  		Epoch:          DefaultEpoch,
   678  		ProposerPolicy: DefaultProposerPolicy,
   679  		SubGroupSize:   DefaultSubGroupSize,
   680  	}
   681  }
   682  
   683  func GetDefaultRewardConfigForGenesis() *RewardConfig {
   684  	return &RewardConfig{
   685  		MintingAmount:          DefaultMintingAmount,
   686  		Ratio:                  DefaultRatio,
   687  		UseGiniCoeff:           DefaultUseGiniCoeff,
   688  		DeferredTxFee:          DefaultDeferredTxFee,
   689  		StakingUpdateInterval:  DefaultStakeUpdateInterval,
   690  		ProposerUpdateInterval: DefaultProposerRefreshInterval,
   691  		MinimumStake:           DefaultMinimumStake,
   692  	}
   693  }
   694  
   695  func GetDefaultRewardConfig() *RewardConfig {
   696  	return &RewardConfig{
   697  		MintingAmount:          DefaultMintingAmount,
   698  		Ratio:                  DefaultRatio,
   699  		Kip82Ratio:             DefaultKip82Ratio,
   700  		UseGiniCoeff:           DefaultUseGiniCoeff,
   701  		DeferredTxFee:          DefaultDeferredTxFee,
   702  		StakingUpdateInterval:  DefaultStakeUpdateInterval,
   703  		ProposerUpdateInterval: DefaultProposerRefreshInterval,
   704  		MinimumStake:           DefaultMinimumStake,
   705  	}
   706  }
   707  
   708  func GetDefaultKIP71Config() *KIP71Config {
   709  	return &KIP71Config{
   710  		LowerBoundBaseFee:         DefaultLowerBoundBaseFee,
   711  		UpperBoundBaseFee:         DefaultUpperBoundBaseFee,
   712  		GasTarget:                 DefaultGasTarget,
   713  		MaxBlockGasUsedForBaseFee: DefaultMaxBlockGasUsedForBaseFee,
   714  		BaseFeeDenominator:        DefaultBaseFeeDenominator,
   715  	}
   716  }
   717  
   718  func GetDefaultCliqueConfig() *CliqueConfig {
   719  	return &CliqueConfig{
   720  		Epoch:  DefaultEpoch,
   721  		Period: DefaultPeriod,
   722  	}
   723  }