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

[RFC-201/205]: EVM-580-Update validator set in stake manager #1431

Merged
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
1 change: 1 addition & 0 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
InitialTrieRoot: types.StringToHash(p.initialStateRoot),
MintableNativeToken: p.mintableNativeToken,
NativeTokenConfig: p.nativeTokenConfig,
MaxValidatorSetSize: p.maxNumValidators,
}

chainConfig := &chain.Chain{
Expand Down
38 changes: 38 additions & 0 deletions consensus/polybft/consensus_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
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/txrelayer"
"github.com/0xPolygon/polygon-edge/types"

Expand Down Expand Up @@ -112,6 +113,9 @@ type consensusRuntime struct {
// manager for state sync bridge transactions
stateSyncManager StateSyncManager

// manager for handling validator stake change and updating validator set
stakeManager StakeManager

// logger instance
logger hcf.Logger
}
Expand Down Expand Up @@ -139,6 +143,10 @@ func newConsensusRuntime(log hcf.Logger, config *runtimeConfig) (*consensusRunti
return nil, err
}

if err := runtime.initStakeManager(log); err != nil {
return nil, err
}

// we need to call restart epoch on runtime to initialize epoch state
runtime.epoch, err = runtime.restartEpoch(runtime.lastBuiltBlock)
if err != nil {
Expand Down Expand Up @@ -211,6 +219,26 @@ func (c *consensusRuntime) initCheckpointManager(logger hcf.Logger) error {
return nil
}

// initStakeManager initializes stake manager
func (c *consensusRuntime) initStakeManager(logger hcf.Logger) error {
txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(c.config.PolyBFTConfig.Bridge.JSONRPCEndpoint))
if err != nil {
return err
}

c.stakeManager = newStakeManager(
logger.Named("stake-manager"),
c.state,
txRelayer,
wallet.NewEcdsaSigner(c.config.Key),
contracts.NewValidatorSetContract,
c.config.PolyBFTConfig.Bridge.CustomSupernetManagerAddr,
int(c.config.PolyBFTConfig.MaxValidatorSetSize),
)

return nil
}

// getGuardedData returns last build block, proposer snapshot and current epochMetadata in a thread-safe manner.
func (c *consensusRuntime) getGuardedData() (guardedDataDTO, error) {
c.lock.RLock()
Expand Down Expand Up @@ -280,6 +308,11 @@ func (c *consensusRuntime) OnBlockInserted(fullBlock *types.FullBlock) {
c.logger.Error("Could not update proposer calculator", "err", err)
}

// handle transfer events that happened in block
if err := c.stakeManager.PostBlock(postBlock); err != nil {
c.logger.Error("failed to post block in stake manager", "err", err)
}

if isEndOfEpoch {
if epoch, err = c.restartEpoch(fullBlock.Block.Header); err != nil {
c.logger.Error("failed to restart epoch after block inserted", "error", err)
Expand Down Expand Up @@ -362,6 +395,11 @@ func (c *consensusRuntime) FSM() error {
if err != nil {
return fmt.Errorf("cannot calculate commit epoch info: %w", err)
}

ff.newValidatorsDelta, err = c.stakeManager.UpdateValidatorSet(epoch.Number, epoch.Validators.Copy())
if err != nil {
return fmt.Errorf("cannot update validator set on epoch ending: %w", err)
}
}

c.logger.Info(
Expand Down
2 changes: 2 additions & 0 deletions consensus/polybft/consensus_runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ func TestConsensusRuntime_OnBlockInserted_EndOfEpoch(t *testing.T) {
lastBuiltBlock: &types.Header{Number: header.Number - 1},
stateSyncManager: &dummyStateSyncManager{},
checkpointManager: &dummyCheckpointManager{},
stakeManager: &dummyStakeManager{},
}
runtime.OnBlockInserted(&types.FullBlock{Block: builtBlock})

Expand Down Expand Up @@ -421,6 +422,7 @@ func TestConsensusRuntime_FSM_EndOfEpoch_BuildCommitEpoch(t *testing.T) {
lastBuiltBlock: lastBuiltBlock,
stateSyncManager: &dummyStateSyncManager{},
checkpointManager: &dummyCheckpointManager{},
stakeManager: &dummyStakeManager{},
}

err := runtime.FSM()
Expand Down
8 changes: 8 additions & 0 deletions consensus/polybft/contractsapi/bindings-gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ func main() {
"StakeAdded",
},
},
{
"ValidatorSet",
gensc.ValidatorSet,
[]string{},
[]string{
"Transfer",
},
},
}

generatedData := &generatedData{}
Expand Down
22 changes: 22 additions & 0 deletions consensus/polybft/contractsapi/contractsapi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion consensus/polybft/contractsapi/gen_sc_data.go

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions consensus/polybft/contractsapi/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,14 @@ func (u *Uptime) AddValidatorUptime(address types.Address, count int64) {
}

var _ StateTransactionInput = &CommitEpochChildValidatorSetFn{}

// IsStake indicates if transfer event (from ERC20 implementation) mints tokens to a non zero address
func (t *TransferEvent) IsStake() bool {
return t.To != types.ZeroAddress && t.From == types.ZeroAddress
}

// IsUnstake indicates if transfer event (from ERC20 implementation) burns tokens from a non zero address
// meaning, it transfers them to zero address
func (t *TransferEvent) IsUnstake() bool {
return t.To == types.ZeroAddress && t.From != types.ZeroAddress
}
11 changes: 1 addition & 10 deletions consensus/polybft/fsm.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,7 @@ func (f *fsm) getValidatorsTransition(delta *ValidatorSetDelta) (AccountSet, err
return nil, err
}

if f.logger.IsDebug() {
var buf bytes.Buffer
for _, v := range nextValidators {
if _, err := buf.WriteString(fmt.Sprintf("%s\n", v.String())); err != nil {
return nil, err
}
}

f.logger.Debug("getValidatorsTransition", "Next validators", buf.String())
}
f.logger.Debug("getValidatorsTransition", "Next validators", nextValidators)

return nextValidators, nil
}
Expand Down
3 changes: 3 additions & 0 deletions consensus/polybft/polybft_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ type PolyBFTConfig struct {
NativeTokenConfig *TokenConfig `json:"nativeTokenConfig"`

InitialTrieRoot types.Hash `json:"initialTrieRoot"`

// MaxValidatorSetSize indicates the maximum size of validator set
MaxValidatorSetSize uint64 `json:"maxValidatorSetSize"`
}

// LoadPolyBFTConfig loads chain config from provided path and unmarshals PolyBFTConfig
Expand Down
Loading