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

Commit

Permalink
Resolve block time from consensus engine parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan-Ethernal committed Apr 6, 2023
1 parent c4784a7 commit 468cdbc
Show file tree
Hide file tree
Showing 14 changed files with 152 additions and 19 deletions.
1 change: 1 addition & 0 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ func (p *genesisParams) initIBFTEngineMap(ibftType fork.IBFTType) {
string(server.IBFTConsensus): map[string]interface{}{
fork.KeyType: ibftType,
fork.KeyValidatorType: p.ibftValidatorType,
fork.KeyBlockTime: p.blockTime,
ibft.KeyEpochSize: p.epochSize,
},
}
Expand Down
3 changes: 2 additions & 1 deletion command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi/artifact"
"github.com/0xPolygon/polygon-edge/helper/common"

"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/command"
Expand Down Expand Up @@ -88,7 +89,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er

polyBftConfig := &polybft.PolyBFTConfig{
InitialValidatorSet: manifest.GenesisValidators,
BlockTime: p.blockTime,
BlockTime: common.Duration{Duration: p.blockTime},
EpochSize: p.epochSize,
SprintSize: p.sprintSize,
EpochReward: p.epochReward,
Expand Down
1 change: 1 addition & 0 deletions command/ibft/switch/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ func appendIBFTForks(
Type: ibftType,
ValidatorType: validatorType,
From: common.JSONNumber{Value: from},
BlockTime: lastFork.BlockTime,
}

switch ibftType {
Expand Down
26 changes: 21 additions & 5 deletions consensus/ibft/fork/fork.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ const (
KeyType = "type"
KeyTypes = "types"
KeyValidatorType = "validator_type"
KeyBlockTime = "blockTime"
)

var (
ErrUndefinedIBFTConfig = errors.New("IBFT config is not defined")
errInvalidBlockTime = errors.New("invalid block time provided")
)

// IBFT Fork represents setting in params.engine.ibft of genesis.json
Expand All @@ -26,6 +28,7 @@ type IBFTFork struct {
Deployment *common.JSONNumber `json:"deployment,omitempty"`
From common.JSONNumber `json:"from"`
To *common.JSONNumber `json:"to,omitempty"`
BlockTime *common.Duration `json:"blockTime,omitempty"`

// PoA
Validators validators.Validators `json:"validators,omitempty"`
Expand All @@ -42,6 +45,7 @@ func (f *IBFTFork) UnmarshalJSON(data []byte) error {
Deployment *common.JSONNumber `json:"deployment,omitempty"`
From common.JSONNumber `json:"from"`
To *common.JSONNumber `json:"to,omitempty"`
BlockTime *common.Duration `json:"blockTime,omitempty"`
Validators interface{} `json:"validators,omitempty"`
MaxValidatorCount *common.JSONNumber `json:"maxValidatorCount,omitempty"`
MinValidatorCount *common.JSONNumber `json:"minValidatorCount,omitempty"`
Expand All @@ -55,6 +59,7 @@ func (f *IBFTFork) UnmarshalJSON(data []byte) error {
f.Deployment = raw.Deployment
f.From = raw.From
f.To = raw.To
f.BlockTime = raw.BlockTime
f.MaxValidatorCount = raw.MaxValidatorCount
f.MinValidatorCount = raw.MinValidatorCount

Expand All @@ -74,11 +79,7 @@ func (f *IBFTFork) UnmarshalJSON(data []byte) error {
return err
}

if err := json.Unmarshal(validatorsBytes, f.Validators); err != nil {
return err
}

return nil
return json.Unmarshal(validatorsBytes, f.Validators)
}

// GetIBFTForks returns IBFT fork configurations from chain config
Expand All @@ -98,13 +99,28 @@ func GetIBFTForks(ibftConfig map[string]interface{}) (IBFTForks, error) {
}
}

var blockTime *common.Duration = nil

blockTimeGeneric, ok := ibftConfig[KeyBlockTime]
if ok {
blockTimeRaw, err := json.Marshal(blockTimeGeneric)
if err != nil {
return nil, errInvalidBlockTime
}

if err := blockTime.UnmarshalJSON(blockTimeRaw); err != nil {
return nil, errInvalidBlockTime
}
}

return IBFTForks{
{
Type: typ,
Deployment: nil,
ValidatorType: validatorType,
From: common.JSONNumber{Value: 0},
To: nil,
BlockTime: blockTime,
},
}, nil
}
Expand Down
6 changes: 5 additions & 1 deletion consensus/ibft/fork/fork_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"testing"
"time"

"github.com/0xPolygon/polygon-edge/helper/common"
testHelper "github.com/0xPolygon/polygon-edge/helper/tests"
Expand Down Expand Up @@ -62,6 +63,7 @@ func TestIBFTForkUnmarshalJSON(t *testing.T) {
data: fmt.Sprintf(`{
"type": "%s",
"validator_type": "%s",
"blockTime": %d,
"validators": [
{
"Address": "%s"
Expand All @@ -72,8 +74,9 @@ func TestIBFTForkUnmarshalJSON(t *testing.T) {
],
"from": %d,
"to": %d
}`,
}`,
PoA, validators.ECDSAValidatorType,
3000000000,
types.StringToAddress("1"), types.StringToAddress("2"),
16, 20,
),
Expand All @@ -86,6 +89,7 @@ func TestIBFTForkUnmarshalJSON(t *testing.T) {
validators.NewECDSAValidator(types.StringToAddress("1")),
validators.NewECDSAValidator(types.StringToAddress("2")),
),
BlockTime: &common.Duration{Duration: 3 * time.Second},
MaxValidatorCount: nil,
MinValidatorCount: nil,
},
Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/consensus_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ func (c *consensusRuntime) FSM() error {
parent,
types.Address(c.config.Key.Address()),
c.config.txPool,
c.config.PolyBFTConfig.BlockTime,
c.config.PolyBFTConfig.BlockTime.Duration,
c.logger,
)

Expand Down
3 changes: 2 additions & 1 deletion consensus/polybft/consensus_runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer"
"github.com/0xPolygon/polygon-edge/consensus/polybft/wallet"
"github.com/0xPolygon/polygon-edge/contracts"
"github.com/0xPolygon/polygon-edge/helper/common"
"github.com/0xPolygon/polygon-edge/types"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -447,7 +448,7 @@ func Test_NewConsensusRuntime(t *testing.T) {
},
EpochSize: 10,
SprintSize: 10,
BlockTime: 2 * time.Second,
BlockTime: common.Duration{Duration: 2 * time.Second},
}

validators := newTestValidators(t, 3).getPublicIdentities()
Expand Down
3 changes: 1 addition & 2 deletions consensus/polybft/polybft_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math/big"
"os"
"path/filepath"
"time"

"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
Expand All @@ -34,7 +33,7 @@ type PolyBFTConfig struct {
SprintSize uint64 `json:"sprintSize"`

// BlockTime is target frequency of blocks production
BlockTime time.Duration `json:"blockTime"`
BlockTime common.Duration `json:"blockTime"`

// Governance is the initial governance address
Governance types.Address `json:"governance"`
Expand Down
2 changes: 0 additions & 2 deletions consensus/polybft/sc_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"math/big"
"strconv"
"testing"
"time"

"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap"
Expand Down Expand Up @@ -278,7 +277,6 @@ func TestIntegration_CommitEpoch(t *testing.T) {

polyBFTConfig := PolyBFTConfig{
InitialValidatorSet: initValidators,
BlockTime: 2 * time.Second,
EpochSize: 24 * 60 * 60 / 2,
SprintSize: 5,
EpochReward: reward,
Expand Down
11 changes: 7 additions & 4 deletions e2e/framework/testserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,13 @@ func (t *TestServer) GenerateGenesis() error {
args = append(args, "--premine", acct.Addr.String()+":0x"+acct.Balance.Text(16))
}

// provide block time flag
// (e2e framework expects BlockTime parameter to be provided in seconds)
if t.Config.BlockTime != 0 {
args = append(args, "--block-time",
(time.Duration(t.Config.BlockTime) * time.Second).String())
}

// add consensus flags
switch t.Config.Consensus {
case ConsensusIBFT:
Expand Down Expand Up @@ -429,10 +436,6 @@ func (t *TestServer) Start(ctx context.Context) error {
args = append(args, "--block-gas-target", *types.EncodeUint64(t.Config.BlockGasTarget))
}

if t.Config.BlockTime != 0 {
args = append(args, "--block-time", strconv.FormatUint(t.Config.BlockTime, 10))
}

if t.Config.IBFTBaseTimeout != 0 {
args = append(args, "--ibft-base-timeout", strconv.FormatUint(t.Config.IBFTBaseTimeout, 10))
}
Expand Down
39 changes: 39 additions & 0 deletions helper/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"path/filepath"
"strconv"
"syscall"
"time"

"github.com/0xPolygon/polygon-edge/helper/hex"
"github.com/0xPolygon/polygon-edge/types"
Expand All @@ -25,6 +26,8 @@ var (
// Our staking repo is written in JS, as are many other clients
// If we use higher value JS will not be able to parse it
MaxSafeJSInt = uint64(math.Pow(2, 53) - 2)

errInvalidDuration = errors.New("invalid duration")
)

// Min returns the strictly lower number
Expand Down Expand Up @@ -237,6 +240,42 @@ func (d *JSONNumber) UnmarshalJSON(data []byte) error {
return nil
}

// Duration is a wrapper struct for time.Duration which implements json (un)marshaling
type Duration struct {
time.Duration
}

func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}

func (d *Duration) UnmarshalJSON(b []byte) error {
var (
v interface{}
err error
)

if err = json.Unmarshal(b, &v); err != nil {
return err
}

switch value := v.(type) {
case float64:
d.Duration = time.Duration(value)

return nil
case string:
d.Duration, err = time.ParseDuration(value)
if err != nil {
return err
}

return nil
}

return errInvalidDuration
}

// GetTerminationSignalCh returns a channel to emit signals by ctrl + c
func GetTerminationSignalCh() <-chan os.Signal {
// wait for the user to quit with ctrl-c
Expand Down
38 changes: 38 additions & 0 deletions helper/common/common_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package common

import (
"encoding/json"
"math/big"
"testing"
"time"

"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -60,3 +62,39 @@ func Test_BigIntDivCeil(t *testing.T) {
require.Equal(t, c.result, BigIntDivCeil(big.NewInt(c.a), big.NewInt(c.b)).Int64())
}
}

func Test_Duration_Marshal_UnmarshalJSON(t *testing.T) {
t.Parallel()

t.Run("use duration standalone", func(t *testing.T) {
t.Parallel()

original := &Duration{Duration: 5 * time.Minute}
originalRaw, err := original.MarshalJSON()
require.NoError(t, err)

other := &Duration{}
require.NoError(t, other.UnmarshalJSON(originalRaw))
require.Equal(t, original, other)
})

t.Run("use duration in wrapper struct", func(t *testing.T) {
t.Parallel()

type timer struct {
Elapsed Duration `json:"elapsed"`
}

dur, err := time.ParseDuration("2h35m21s")
require.NoError(t, err)

origTimer := &timer{Elapsed: Duration{dur}}

timerRaw, err := json.Marshal(origTimer)
require.NoError(t, err)

var otherTimer *timer
require.NoError(t, json.Unmarshal(timerRaw, &otherTimer))
require.Equal(t, origTimer, otherTimer)
})
}
1 change: 0 additions & 1 deletion server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ type Config struct {
PriceLimit uint64
MaxAccountEnqueued uint64
MaxSlots uint64
BlockTime uint64

Telemetry *Telemetry
Network *network.Config
Expand Down
Loading

0 comments on commit 468cdbc

Please sign in to comment.