Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce block tracker poll interval #1887

Merged
merged 5 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,13 @@ func setFlags(cmd *cobra.Command) {
command.DefaultGenesisBaseFeeChangeDenom,
"default base fee change denominator the value to bound the amount the base fee can change between blocks.",
)

cmd.Flags().DurationVar(
&params.blockTrackerPollInterval,
blockTrackerPollIntervalFlag,
defaultBlockTrackerPollInterval,
"interval (number of seconds) at which block tracker polls for latest block at rootchain",
)
}

// Governance
Expand Down
65 changes: 41 additions & 24 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,30 @@ import (
)

const (
dirFlag = "dir"
nameFlag = "name"
premineFlag = "premine"
chainIDFlag = "chain-id"
epochSizeFlag = "epoch-size"
epochRewardFlag = "epoch-reward"
blockGasLimitFlag = "block-gas-limit"
burnContractFlag = "burn-contract"
posFlag = "pos"
minValidatorCount = "min-validator-count"
maxValidatorCount = "max-validator-count"
nativeTokenConfigFlag = "native-token-config"
rewardTokenCodeFlag = "reward-token-code"
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"
governorAdminFlag = "governor-admin"
proposalQuorumFlag = "proposal-quorum"
proxyContractsAdminFlag = "proxy-contracts-admin"
dirFlag = "dir"
nameFlag = "name"
premineFlag = "premine"
chainIDFlag = "chain-id"
epochSizeFlag = "epoch-size"
epochRewardFlag = "epoch-reward"
blockGasLimitFlag = "block-gas-limit"
burnContractFlag = "burn-contract"
posFlag = "pos"
minValidatorCount = "min-validator-count"
maxValidatorCount = "max-validator-count"
nativeTokenConfigFlag = "native-token-config"
rewardTokenCodeFlag = "reward-token-code"
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"
governorAdminFlag = "governor-admin"
proposalQuorumFlag = "proposal-quorum"
proxyContractsAdminFlag = "proxy-contracts-admin"
blockTrackerPollIntervalFlag = "block-tracker-poll-interval"

defaultNativeTokenName = "Polygon"
defaultNativeTokenSymbol = "MATIC"
Expand Down Expand Up @@ -76,6 +77,7 @@ var (
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")
errBlockTrackerPollInterval = errors.New("block tracker poll interval must be greater than 0")
)

type genesisParams struct {
Expand Down Expand Up @@ -156,7 +158,8 @@ type genesisParams struct {
proposalQuorum uint64
governorAdmin string

proxyContractsAdmin string
proxyContractsAdmin string
blockTrackerPollInterval time.Duration
}

func (p *genesisParams) validateFlags() error {
Expand Down Expand Up @@ -204,6 +207,10 @@ func (p *genesisParams) validateFlags() error {
if err := p.validateProxyContractsAdmin(); err != nil {
return err
}

if err := p.validateBlockTrackerPollInterval(); err != nil {
return err
}
}

// Check if the genesis file already exists
Expand Down Expand Up @@ -560,6 +567,16 @@ func (p *genesisParams) validateGovernorAdminAddr() error {
return nil
}

// validateBlockTrackerPollInterval validates block tracker block interval
// which can not be 0
func (p *genesisParams) validateBlockTrackerPollInterval() error {
if p.blockTrackerPollInterval == 0 {
return helper.ErrBlockTrackerPollInterval
}

return nil
}

// validateBurnContract validates burn contract. If native token is mintable,
// burn contract flag must not be set. If native token is non mintable only one burn contract
// can be set and the specified address will be used to predeploy default EIP1559 burn contract.
Expand Down
2 changes: 2 additions & 0 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const (
defaultVotingPeriod = "10000" // in blocks
defaultVoteProposalThreshold = "1000" // in blocks
defaultProposalQuorumPercentage = uint64(67) // percentage
defaultBlockTrackerPollInterval = time.Second

accessListsOwnerFlag = "access-lists-owner" // #nosec G101
contractDeployerAllowListAdminFlag = "contract-deployer-allow-list-admin"
Expand Down Expand Up @@ -214,6 +215,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
NetworkParamsAddr: contracts.NetworkParamsContract,
ForkParamsAddr: contracts.ForkParamsContract,
},
BlockTrackerPollInterval: common.Duration{Duration: p.blockTrackerPollInterval},
}

// Disable london hardfork if burn contract address is not provided
Expand Down
2 changes: 2 additions & 0 deletions command/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"google.golang.org/grpc/credentials/insecure"
)

var ErrBlockTrackerPollInterval = errors.New("block tracker poll interval must be greater than 0")

type ClientCloseResult struct {
Message string `json:"message"`
}
Expand Down
25 changes: 16 additions & 9 deletions command/server/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"strings"
"time"

"github.com/0xPolygon/polygon-edge/network"
"github.com/hashicorp/hcl"
Expand Down Expand Up @@ -32,8 +33,9 @@ type Config struct {
JSONLogFormat bool `json:"json_log_format" yaml:"json_log_format"`
CorsAllowedOrigins []string `json:"cors_allowed_origins" yaml:"cors_allowed_origins"`

Relayer bool `json:"relayer" yaml:"relayer"`
NumBlockConfirmations uint64 `json:"num_block_confirmations" yaml:"num_block_confirmations"`
Relayer bool `json:"relayer" yaml:"relayer"`
NumBlockConfirmations uint64 `json:"num_block_confirmations" yaml:"num_block_confirmations"`
RelayerTrackerPollInterval time.Duration `json:"relayer_tracker_poll_interval" yaml:"relayer_tracker_poll_interval"`

ConcurrentRequestsDebug uint64 `json:"concurrent_requests_debug" yaml:"concurrent_requests_debug"`
WebSocketReadLimit uint64 `json:"web_socket_read_limit" yaml:"web_socket_read_limit"`
Expand Down Expand Up @@ -90,6 +92,10 @@ const (
// If a message exceeds the limit,
// the connection sends a close message to the peer and returns ErrReadLimit to the application.
DefaultWebSocketReadLimit uint64 = 8192

// DefaultRelayerTrackerPollInterval specifies time interval after which relayer node's event tracker
// polls child chain to get the latest block
DefaultRelayerTrackerPollInterval time.Duration = time.Second
)

// DefaultConfig returns the default server configuration
Expand Down Expand Up @@ -122,13 +128,14 @@ func DefaultConfig() *Config {
Headers: &Headers{
AccessControlAllowOrigins: []string{"*"},
},
LogFilePath: "",
JSONRPCBatchRequestLimit: DefaultJSONRPCBatchRequestLimit,
JSONRPCBlockRangeLimit: DefaultJSONRPCBlockRangeLimit,
Relayer: false,
NumBlockConfirmations: DefaultNumBlockConfirmations,
ConcurrentRequestsDebug: DefaultConcurrentRequestsDebug,
WebSocketReadLimit: DefaultWebSocketReadLimit,
LogFilePath: "",
JSONRPCBatchRequestLimit: DefaultJSONRPCBatchRequestLimit,
JSONRPCBlockRangeLimit: DefaultJSONRPCBlockRangeLimit,
Relayer: false,
NumBlockConfirmations: DefaultNumBlockConfirmations,
ConcurrentRequestsDebug: DefaultConcurrentRequestsDebug,
WebSocketReadLimit: DefaultWebSocketReadLimit,
RelayerTrackerPollInterval: DefaultRelayerTrackerPollInterval,
}
}

Expand Down
4 changes: 4 additions & 0 deletions command/server/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ func (p *serverParams) initRawParams() error {

p.relayer = p.rawConfig.Relayer

if p.relayer && p.rawConfig.RelayerTrackerPollInterval == 0 {
return helper.ErrBlockTrackerPollInterval
}

return p.initAddresses()
}

Expand Down
7 changes: 5 additions & 2 deletions command/server/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ const (

concurrentRequestsDebugFlag = "concurrent-requests-debug"
webSocketReadLimitFlag = "websocket-read-limit"

relayerTrackerPollIntervalFlag = "relayer-poll-interval"
)

// Flags that are deprecated, but need to be preserved for
Expand Down Expand Up @@ -185,7 +187,8 @@ func (p *serverParams) generateConfig() *server.Config {
JSONLogFormat: p.rawConfig.JSONLogFormat,
LogFilePath: p.logFileLocation,

Relayer: p.relayer,
NumBlockConfirmations: p.rawConfig.NumBlockConfirmations,
Relayer: p.relayer,
NumBlockConfirmations: p.rawConfig.NumBlockConfirmations,
RelayerTrackerPollInterval: p.rawConfig.RelayerTrackerPollInterval,
}
}
7 changes: 7 additions & 0 deletions command/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ func setFlags(cmd *cobra.Command) {
"maximum size in bytes for a message read from the peer by websocket",
)

cmd.Flags().DurationVar(
&params.rawConfig.RelayerTrackerPollInterval,
goran-ethernal marked this conversation as resolved.
Show resolved Hide resolved
relayerTrackerPollIntervalFlag,
defaultConfig.RelayerTrackerPollInterval,
"interval (number of seconds) at which relayer's tracker polls for latest block at childchain",
igorcrevar marked this conversation as resolved.
Show resolved Hide resolved
)

setLegacyFlags(cmd)

setDevFlags(cmd)
Expand Down
4 changes: 4 additions & 0 deletions consensus/polybft/common/polybft_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ type PolyBFTConfig struct {
// ProxyContractsAdmin is the address that will have the privilege to change both the proxy
// implementation address and the admin
ProxyContractsAdmin types.Address `json:"proxyContractsAdmin,omitempty"`

// BlockTrackerPollInterval specifies interval
// at which block tracker polls for blocks on a rootchain
BlockTrackerPollInterval common.Duration `json:"blockTrackerPollInterval,omitempty"`
goran-ethernal marked this conversation as resolved.
Show resolved Hide resolved
}

// LoadPolyBFTConfig loads chain config from provided path and unmarshals PolyBFTConfig
Expand Down
17 changes: 9 additions & 8 deletions consensus/polybft/consensus_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,14 +195,15 @@ func (c *consensusRuntime) initStateSyncManager(logger hcf.Logger) error {
logger.Named("state-sync-manager"),
c.config.State,
&stateSyncConfig{
key: c.config.Key,
stateSenderAddr: stateSenderAddr,
stateSenderStartBlock: c.config.GenesisConfig.Bridge.EventTrackerStartBlocks[stateSenderAddr],
jsonrpcAddr: c.config.GenesisConfig.Bridge.JSONRPCEndpoint,
dataDir: c.config.DataDir,
topic: c.config.bridgeTopic,
maxCommitmentSize: maxCommitmentSize,
numBlockConfirmations: c.config.numBlockConfirmations,
key: c.config.Key,
stateSenderAddr: stateSenderAddr,
stateSenderStartBlock: c.config.GenesisConfig.Bridge.EventTrackerStartBlocks[stateSenderAddr],
jsonrpcAddr: c.config.GenesisConfig.Bridge.JSONRPCEndpoint,
dataDir: c.config.DataDir,
topic: c.config.bridgeTopic,
maxCommitmentSize: maxCommitmentSize,
numBlockConfirmations: c.config.numBlockConfirmations,
blockTrackerPollInterval: c.config.GenesisConfig.BlockTrackerPollInterval.Duration,
},
c,
)
Expand Down
35 changes: 19 additions & 16 deletions consensus/polybft/state_sync_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import (
"fmt"
"path"
"sync"
"time"

"github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap"
"github.com/0xPolygon/polygon-edge/consensus/polybft/common"
polybftCommon "github.com/0xPolygon/polygon-edge/consensus/polybft/common"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
polybftProto "github.com/0xPolygon/polygon-edge/consensus/polybft/proto"
bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer"
Expand Down Expand Up @@ -39,8 +40,8 @@ type StateSyncManager interface {
Close()
Commitment(blockNumber uint64) (*CommitmentMessageSigned, error)
GetStateSyncProof(stateSyncID uint64) (types.Proof, error)
PostBlock(req *common.PostBlockRequest) error
PostEpoch(req *common.PostEpochRequest) error
PostBlock(req *polybftCommon.PostBlockRequest) error
PostEpoch(req *polybftCommon.PostEpochRequest) error
}

var _ StateSyncManager = (*dummyStateSyncManager)(nil)
Expand All @@ -53,22 +54,23 @@ func (n *dummyStateSyncManager) Close() {}
func (n *dummyStateSyncManager) Commitment(blockNumber uint64) (*CommitmentMessageSigned, error) {
return nil, nil
}
func (n *dummyStateSyncManager) PostBlock(req *common.PostBlockRequest) error { return nil }
func (n *dummyStateSyncManager) PostEpoch(req *common.PostEpochRequest) error { return nil }
func (n *dummyStateSyncManager) PostBlock(req *polybftCommon.PostBlockRequest) error { return nil }
func (n *dummyStateSyncManager) PostEpoch(req *polybftCommon.PostEpochRequest) error { return nil }
func (n *dummyStateSyncManager) GetStateSyncProof(stateSyncID uint64) (types.Proof, error) {
return types.Proof{}, nil
}

// stateSyncConfig holds the configuration data of state sync manager
type stateSyncConfig struct {
stateSenderAddr types.Address
stateSenderStartBlock uint64
jsonrpcAddr string
dataDir string
topic topic
key *wallet.Key
maxCommitmentSize uint64
numBlockConfirmations uint64
stateSenderAddr types.Address
stateSenderStartBlock uint64
jsonrpcAddr string
dataDir string
topic topic
key *wallet.Key
maxCommitmentSize uint64
numBlockConfirmations uint64
blockTrackerPollInterval time.Duration
}

var _ StateSyncManager = (*stateSyncManager)(nil)
Expand Down Expand Up @@ -138,7 +140,8 @@ func (s *stateSyncManager) initTracker() error {
s,
s.config.numBlockConfirmations,
s.config.stateSenderStartBlock,
s.logger)
s.logger,
s.config.blockTrackerPollInterval)

go func() {
<-s.closeCh
Expand Down Expand Up @@ -374,7 +377,7 @@ func (s *stateSyncManager) getAggSignatureForCommitmentMessage(blockNumber uint6

// PostEpoch notifies the state sync manager that an epoch has changed,
// so that it can discard any previous epoch commitments, and build a new one (since validator set changed)
func (s *stateSyncManager) PostEpoch(req *common.PostEpochRequest) error {
func (s *stateSyncManager) PostEpoch(req *polybftCommon.PostEpochRequest) error {
s.lock.Lock()

s.pendingCommitments = nil
Expand All @@ -398,7 +401,7 @@ func (s *stateSyncManager) PostEpoch(req *common.PostEpochRequest) error {

// PostBlock notifies state sync manager that a block was finalized,
// so that it can build state sync proofs if a block has a commitment submission transaction
func (s *stateSyncManager) PostBlock(req *common.PostBlockRequest) error {
func (s *stateSyncManager) PostBlock(req *polybftCommon.PostBlockRequest) error {
commitment, err := getCommitmentMessageSignedTx(req.FullBlock.Block.Transactions)
if err != nil {
return err
Expand Down
5 changes: 5 additions & 0 deletions consensus/polybft/statesyncrelayer/state_sync_relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"path"
"strings"
"time"

"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/contracts"
Expand All @@ -30,6 +31,7 @@ type StateSyncRelayer struct {
txRelayer txrelayer.TxRelayer
key ethgo.Key
closeCh chan struct{}
pollInterval time.Duration
}

func sanitizeRPCEndpoint(rpcEndpoint string) string {
Expand All @@ -52,6 +54,7 @@ func NewRelayer(
stateReceiverTrackerStartBlock uint64,
logger hcf.Logger,
key ethgo.Key,
pollInterval time.Duration,
) *StateSyncRelayer {
endpoint := sanitizeRPCEndpoint(rpcEndpoint)

Expand All @@ -78,6 +81,7 @@ func NewRelayer(
key: key,
closeCh: make(chan struct{}),
eventTrackerStartBlock: stateReceiverTrackerStartBlock,
pollInterval: pollInterval,
}
}

Expand All @@ -90,6 +94,7 @@ func (r *StateSyncRelayer) Start() error {
0, // sidechain (Polygon POS) is instant finality, so no need to wait
r.eventTrackerStartBlock,
r.logger,
r.pollInterval,
)

ctx, cancelFn := context.WithCancel(context.Background())
Expand Down
Loading
Loading