Skip to content
This repository has been archived by the owner on Dec 4, 2024. It is now read-only.

Commit

Permalink
Introduce baseFeeChangeDenom network parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan-Ethernal committed Sep 7, 2023
1 parent c3da0d4 commit 0760205
Show file tree
Hide file tree
Showing 24 changed files with 290 additions and 204 deletions.
23 changes: 13 additions & 10 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,19 @@ import (
"sync"
"sync/atomic"

"github.com/hashicorp/go-hclog"
lru "github.com/hashicorp/golang-lru"

"github.com/0xPolygon/polygon-edge/blockchain/storage"
"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/forkmanager"
"github.com/0xPolygon/polygon-edge/helper/common"
"github.com/0xPolygon/polygon-edge/state"
"github.com/0xPolygon/polygon-edge/types"
"github.com/0xPolygon/polygon-edge/types/buildroot"

"github.com/hashicorp/go-hclog"
lru "github.com/hashicorp/golang-lru"
)

const (
// defaultBaseFeeChangeDenom is the value to bound the amount the base fee can change between blocks.
defaultBaseFeeChangeDenom = 8

// blockGasTargetDivisor is the bound divisor of the gas limit, used in update calculations
blockGasTargetDivisor uint64 = 1024

Expand Down Expand Up @@ -1381,22 +1379,27 @@ func (b *Blockchain) CalculateBaseFee(parent *types.Header) uint64 {
// If the parent block used more gas than its target, the baseFee should increase.
if parent.GasUsed > parentGasTarget {
gasUsedDelta := parent.GasUsed - parentGasTarget
baseFeeDelta := calcBaseFeeDelta(gasUsedDelta, parentGasTarget, parent.BaseFee)
baseFeeDelta := b.calcBaseFeeDelta(gasUsedDelta, parentGasTarget, parent.BaseFee)

return parent.BaseFee + common.Max(baseFeeDelta, 1)
}

// Otherwise, if the parent block used less gas than its target, the baseFee should decrease.
gasUsedDelta := parentGasTarget - parent.GasUsed
baseFeeDelta := calcBaseFeeDelta(gasUsedDelta, parentGasTarget, parent.BaseFee)
baseFeeDelta := b.calcBaseFeeDelta(gasUsedDelta, parentGasTarget, parent.BaseFee)

return common.Max(parent.BaseFee-baseFeeDelta, 0)
}

func calcBaseFeeDelta(gasUsedDelta, parentGasTarget, baseFee uint64) uint64 {
func (b *Blockchain) calcBaseFeeDelta(gasUsedDelta, parentGasTarget, baseFee uint64) uint64 {
baseFeeChangeDenom := chain.BaseFeeChangeDenom
if forkmanager.GetInstance().IsForkEnabled(chain.Governance, b.Header().Number) {
baseFeeChangeDenom = b.Config().BaseFeeChangeDenom
}

y := baseFee * gasUsedDelta / parentGasTarget

return y / defaultBaseFeeChangeDenom
return y / baseFeeChangeDenom
}

func (b *Blockchain) writeBatchAndUpdate(
Expand Down
3 changes: 3 additions & 0 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import (
)

const (
// BaseFeeChangeDenom is the value to bound the amount the base fee can change between blocks
BaseFeeChangeDenom = uint64(8)

// GenesisBaseFeeEM is the initial base fee elasticity multiplier for EIP-1559 blocks.
GenesisBaseFeeEM = 2

Expand Down
3 changes: 3 additions & 0 deletions chain/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ type Params struct {
Engine map[string]interface{} `json:"engine"`
BlockGasTarget uint64 `json:"blockGasTarget"`

// BaseFeeChangeDenom is the value to bound the amount the base fee can change between blocks
BaseFeeChangeDenom uint64 `json:"baseFeeChangeDenom,omitempty"`

// Access control configuration
AccessListsOwner *types.Address `json:"accessListsOwner,omitempty"`
ContractDeployerAllowList *AddressListConfig `json:"contractDeployerAllowList,omitempty"`
Expand Down
15 changes: 8 additions & 7 deletions command/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import (
)

const (
DefaultGenesisFileName = "genesis.json"
DefaultChainName = "polygon-edge"
DefaultChainID = 100
DefaultConsensus = server.PolyBFTConsensus
DefaultGenesisGasUsed = 458752 // 0x70000
DefaultGenesisGasLimit = 5242880 // 0x500000
DefaultGenesisBaseFeeEM = chain.GenesisBaseFeeEM
DefaultGenesisFileName = "genesis.json"
DefaultChainName = "polygon-edge"
DefaultChainID = 100
DefaultConsensus = server.PolyBFTConsensus
DefaultGenesisGasUsed = 458752 // 0x70000
DefaultGenesisGasLimit = 5242880 // 0x500000
DefaultGenesisBaseFeeEM = chain.GenesisBaseFeeEM
DefaultGenesisBaseFeeChangeDenom = chain.BaseFeeChangeDenom
)

var (
Expand Down
7 changes: 7 additions & 0 deletions command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,13 @@ func setFlags(cmd *cobra.Command) {
defaultWithdrawalWaitPeriod,
"number of epochs after which withdrawal can be done from child chain",
)

cmd.Flags().Uint64Var(
&params.baseFeeChangeDenom,
baseFeeChangeDenomFlag,
command.DefaultGenesisBaseFeeChangeDenom,
"default base fee change denominator the value to bound the amount the base fee can change between blocks.",
)
}

// Governance
Expand Down
14 changes: 11 additions & 3 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const (
rewardWalletFlag = "reward-wallet"
checkpointIntervalFlag = "checkpoint-interval"
withdrawalWaitPeriodFlag = "withdrawal-wait-period"
baseFeeChangeDenomFlag = "base-fee-change-denom"
voteDelayFlag = "vote-delay"
votePeriodFlag = "vote-period"
voteProposalThresholdFlag = "vote-proposal-threshold"
Expand Down Expand Up @@ -72,6 +73,7 @@ var (
errReserveAccMustBePremined = errors.New("it is mandatory to premine reserve account (0x0 address)")
errInvalidVotingPeriod = errors.New("voting period can not be zero")
errInvalidGovernorAdmin = errors.New("governor admin address must be defined")
errBaseFeeChangeDenomZero = errors.New("base fee change denominator must be greater than 0")
)

type genesisParams struct {
Expand Down Expand Up @@ -143,6 +145,7 @@ type genesisParams struct {

checkpointInterval uint64
withdrawalWaitPeriod uint64
baseFeeChangeDenom uint64

// governance
voteDelay string
Expand All @@ -169,6 +172,10 @@ func (p *genesisParams) validateFlags() error {
return err
}

if p.baseFeeChangeDenom == 0 {
return errBaseFeeChangeDenomZero
}

if p.isPolyBFTConsensus() {
if err := p.extractNativeTokenMetadata(); err != nil {
return err
Expand Down Expand Up @@ -421,9 +428,10 @@ func (p *genesisParams) initGenesisConfig() error {
GasUsed: command.DefaultGenesisGasUsed,
},
Params: &chain.Params{
ChainID: int64(p.chainID),
Forks: enabledForks,
Engine: p.consensusEngineConfig,
ChainID: int64(p.chainID),
Forks: enabledForks,
Engine: p.consensusEngineConfig,
BaseFeeChangeDenom: p.baseFeeChangeDenom,
},
Bootnodes: p.bootnodes,
}
Expand Down
1 change: 1 addition & 0 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
Engine: map[string]interface{}{
string(server.PolyBFTConsensus): polyBftConfig,
},
BaseFeeChangeDenom: p.baseFeeChangeDenom,
},
Bootnodes: p.bootnodes,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func runCommand(cmd *cobra.Command, _ []string) error {
return fmt.Errorf("failed to read chain configuration: %w", err)
}

consensusConfig, err := polyCommon.GetPolyBFTConfig(chainConfig)
consensusConfig, err := polyCommon.GetPolyBFTConfig(chainConfig.Params)
if err != nil {
return fmt.Errorf("failed to retrieve consensus configuration: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion command/rootchain/supernet/supernet.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func runCommand(cmd *cobra.Command, _ []string) error {
return fmt.Errorf("failed to read chain configuration: %w", err)
}

consensusConfig, err := polyCommon.GetPolyBFTConfig(chainConfig)
consensusConfig, err := polyCommon.GetPolyBFTConfig(chainConfig.Params)
if err != nil {
return fmt.Errorf("failed to retrieve consensus configuration: %w", err)
}
Expand Down
11 changes: 8 additions & 3 deletions consensus/polybft/common/polybft_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type PolyBFTConfig struct {
// NativeTokenConfig defines name, symbol and decimal count of the native token
NativeTokenConfig *TokenConfig `json:"nativeTokenConfig"`

// InitialTrieRoot represents a pre-existing state root hash
InitialTrieRoot types.Hash `json:"initialTrieRoot"`

// SupernetID indicates ID of given supernet generated by stake manager contract
Expand All @@ -55,6 +56,10 @@ type PolyBFTConfig struct {
// WithdrawalWaitPeriod indicates a number of epochs after which withdrawal can be done from child chain
WithdrawalWaitPeriod uint64 `json:"withdrawalWaitPeriod,omitempty"`

// TODO: @Stefan-Ethernal REMOVE!

Check failure on line 59 in consensus/polybft/common/polybft_config.go

View workflow job for this annotation

GitHub Actions / golangci_lint

consensus/polybft/common/polybft_config.go:59: Line contains TODO/BUG/FIXME: "TODO: @Stefan-Ethernal REMOVE!" (godox)

Check failure on line 59 in consensus/polybft/common/polybft_config.go

View workflow job for this annotation

GitHub Actions / golangci_lint

consensus/polybft/common/polybft_config.go:59: Line contains TODO/BUG/FIXME: "TODO: @Stefan-Ethernal REMOVE!" (godox)
// BaseFeeChangeDenom is the value to bound the amount the base fee can change between blocks
BaseFeeChangeDenom uint64 `json:"baseFeeChangeDenom,omitempty"`

// RewardConfig defines rewards configuration
RewardConfig *RewardsConfig `json:"rewardConfig"`

Expand All @@ -72,7 +77,7 @@ func LoadPolyBFTConfig(chainConfigFile string) (PolyBFTConfig, error) {
return PolyBFTConfig{}, err
}

polybftConfig, err := GetPolyBFTConfig(chainCfg)
polybftConfig, err := GetPolyBFTConfig(chainCfg.Params)
if err != nil {
return PolyBFTConfig{}, err
}
Expand All @@ -81,8 +86,8 @@ func LoadPolyBFTConfig(chainConfigFile string) (PolyBFTConfig, error) {
}

// GetPolyBFTConfig deserializes provided chain config and returns PolyBFTConfig
func GetPolyBFTConfig(chainConfig *chain.Chain) (PolyBFTConfig, error) {
consensusConfigJSON, err := json.Marshal(chainConfig.Params.Engine[ConsensusName])
func GetPolyBFTConfig(chainParams *chain.Params) (PolyBFTConfig, error) {
consensusConfigJSON, err := json.Marshal(chainParams.Engine[ConsensusName])
if err != nil {
return PolyBFTConfig{}, err
}
Expand Down
32 changes: 19 additions & 13 deletions consensus/polybft/consensus_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ type guardedDataDTO struct {

// runtimeConfig is a struct that holds configuration data for given consensus runtime
type runtimeConfig struct {
GenesisPolyBFTConfig *common.PolyBFTConfig
genesisParams *chain.Params
GenesisConfig *common.PolyBFTConfig
Forks *chain.Forks
DataDir string
Key *wallet.Key
Expand Down Expand Up @@ -189,15 +190,15 @@ func (c *consensusRuntime) close() {
// if bridge is not enabled, then a dummy state sync manager will be used
func (c *consensusRuntime) initStateSyncManager(logger hcf.Logger) error {
if c.IsBridgeEnabled() {
stateSenderAddr := c.config.GenesisPolyBFTConfig.Bridge.StateSenderAddr
stateSenderAddr := c.config.GenesisConfig.Bridge.StateSenderAddr
stateSyncManager := newStateSyncManager(
logger.Named("state-sync-manager"),
c.config.State,
&stateSyncConfig{
key: c.config.Key,
stateSenderAddr: stateSenderAddr,
stateSenderStartBlock: c.config.GenesisPolyBFTConfig.Bridge.EventTrackerStartBlocks[stateSenderAddr],
jsonrpcAddr: c.config.GenesisPolyBFTConfig.Bridge.JSONRPCEndpoint,
stateSenderStartBlock: c.config.GenesisConfig.Bridge.EventTrackerStartBlocks[stateSenderAddr],
jsonrpcAddr: c.config.GenesisConfig.Bridge.JSONRPCEndpoint,
dataDir: c.config.DataDir,
topic: c.config.bridgeTopic,
maxCommitmentSize: maxCommitmentSize,
Expand All @@ -220,15 +221,15 @@ func (c *consensusRuntime) initCheckpointManager(logger hcf.Logger) error {
if c.IsBridgeEnabled() {
// enable checkpoint manager
txRelayer, err := txrelayer.NewTxRelayer(
txrelayer.WithIPAddress(c.config.GenesisPolyBFTConfig.Bridge.JSONRPCEndpoint),
txrelayer.WithIPAddress(c.config.GenesisConfig.Bridge.JSONRPCEndpoint),
txrelayer.WithWriter(logger.StandardWriter(&hcf.StandardLoggerOptions{})))
if err != nil {
return err
}

c.checkpointManager = newCheckpointManager(
wallet.NewEcdsaSigner(c.config.Key),
c.config.GenesisPolyBFTConfig.Bridge.CheckpointManagerAddr,
c.config.GenesisConfig.Bridge.CheckpointManagerAddr,
txRelayer,
c.config.blockchain,
c.config.polybftBackend,
Expand All @@ -244,7 +245,7 @@ func (c *consensusRuntime) initCheckpointManager(logger hcf.Logger) error {
// initStakeManager initializes stake manager
func (c *consensusRuntime) initStakeManager(logger hcf.Logger) error {
rootRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(
c.config.GenesisPolyBFTConfig.Bridge.JSONRPCEndpoint))
c.config.GenesisConfig.Bridge.JSONRPCEndpoint))
if err != nil {
return err
}
Expand All @@ -255,7 +256,7 @@ func (c *consensusRuntime) initStakeManager(logger hcf.Logger) error {
rootRelayer,
wallet.NewEcdsaSigner(c.config.Key),
contracts.ValidatorSetContract,
c.config.GenesisPolyBFTConfig.Bridge.CustomSupernetManagerAddr,
c.config.GenesisConfig.Bridge.CustomSupernetManagerAddr,
c.config.blockchain,
)

Expand All @@ -265,12 +266,12 @@ func (c *consensusRuntime) initStakeManager(logger hcf.Logger) error {
// initGovernanceManager initializes governance manager
func (c *consensusRuntime) initGovernanceManager(logger hcf.Logger) error {
governanceManager, err := newGovernanceManager(
c.config.GenesisPolyBFTConfig,
c.config.genesisParams,
c.config.GenesisConfig,
logger.Named("governance-manager"),
c.state,
c.config.blockchain,
)

if err != nil {
return err
}
Expand Down Expand Up @@ -318,7 +319,7 @@ func (c *consensusRuntime) getGuardedData() (guardedDataDTO, error) {
func (c *consensusRuntime) IsBridgeEnabled() bool {
// this is enough to check, because bridge config is not something
// that can be changed through governance
return c.config.GenesisPolyBFTConfig.IsBridgeEnabled()
return c.config.GenesisConfig.IsBridgeEnabled()
}

// OnBlockInserted is called whenever fsm or syncer inserts new block
Expand Down Expand Up @@ -570,7 +571,12 @@ func (c *consensusRuntime) restartEpoch(header *types.Header) (*epochMetadata, e
return nil, err
}

currentConfig, err := c.governanceManager.GetClientConfig()
currentParams, err := c.governanceManager.GetClientConfig()
if err != nil {
return nil, err
}

currentPolyConfig, err := common.GetPolyBFTConfig(currentParams)
if err != nil {
return nil, err
}
Expand All @@ -579,7 +585,7 @@ func (c *consensusRuntime) restartEpoch(header *types.Header) (*epochMetadata, e
Number: epochNumber,
Validators: validatorSet,
FirstBlockInEpoch: firstBlockInEpoch,
CurrentClientConfig: currentConfig,
CurrentClientConfig: &currentPolyConfig,
}, nil
}

Expand Down
Loading

0 comments on commit 0760205

Please sign in to comment.