Skip to content

Commit

Permalink
[EVM-685]: Remove premining of validator balances on L2 for non-minta…
Browse files Browse the repository at this point in the history
…ble tokens (#1598)

* Remove premining of balance of validators on L2

* Don't allow premine if native token is non-mintable

* E2E tests fix

* Rebase fix

* Lint fix
  • Loading branch information
goran-ethernal committed Jun 13, 2023
1 parent d9b8aae commit 470ffb8
Show file tree
Hide file tree
Showing 19 changed files with 344 additions and 183 deletions.
10 changes: 0 additions & 10 deletions command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,6 @@ func setFlags(cmd *cobra.Command) {
"validators defined by user (format: <P2P multi address>:<ECDSA address>:<public BLS key>)",
)

cmd.Flags().StringArrayVar(
&params.stakes,
stakeFlag,
[]string{},
fmt.Sprintf(
"validators staked amount (format: <address>[:<amount>]). Default stake amount: %d",
command.DefaultStake,
),
)

cmd.MarkFlagsMutuallyExclusive(validatorsFlag, validatorsPathFlag)
cmd.MarkFlagsMutuallyExclusive(validatorsFlag, validatorsPrefixFlag)

Expand Down
1 change: 0 additions & 1 deletion command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ type genesisParams struct {
// PolyBFT
validatorsPath string
validatorsPrefixPath string
stakes []string
validators []string
sprintSize uint64
blockTime time.Duration
Expand Down
66 changes: 19 additions & 47 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/0xPolygon/polygon-edge/command"
"github.com/0xPolygon/polygon-edge/command/helper"
"github.com/0xPolygon/polygon-edge/consensus/polybft"
"github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi/artifact"
"github.com/0xPolygon/polygon-edge/consensus/polybft/validator"
Expand All @@ -27,7 +26,6 @@ import (
)

const (
stakeFlag = "stake"
validatorsFlag = "validators"
validatorsPathFlag = "validators-path"
validatorsPrefixFlag = "validators-prefix"
Expand Down Expand Up @@ -68,6 +66,8 @@ const (

var (
errNoGenesisValidators = errors.New("genesis validators aren't provided")
errNoPremineAllowed = errors.New("native token is not mintable, so no premine is allowed " +
"except for zero address and reward wallet if native token is used as reward token")
)

// generatePolyBftChainConfig creates and persists polybft chain configuration to the provided file path
Expand All @@ -93,6 +93,16 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
return fmt.Errorf("invalid reward wallet configuration provided '%s' : %w", p.rewardWallet, err)
}

if !p.nativeTokenConfig.IsMintable {
// validate premine map, no premine is allowed if token is not mintable,
// except for the reward wallet (if native token is used as reward token) and zero address
for a := range premineBalances {
if a != types.ZeroAddress && (p.rewardTokenCode != "" || a != walletPremineInfo.address) {
return errNoPremineAllowed
}
}
}

var (
rewardTokenByteCode []byte
rewardTokenAddr = contracts.NativeERC20TokenContract
Expand Down Expand Up @@ -169,26 +179,12 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
Bootnodes: p.bootnodes,
}

totalStake := big.NewInt(0)

for _, validator := range initialValidators {
// increment total stake
totalStake.Add(totalStake, validator.Stake)
}

// deploy genesis contracts
allocs, err := p.deployContracts(totalStake, rewardTokenByteCode, polyBftConfig)
allocs, err := p.deployContracts(rewardTokenByteCode, polyBftConfig)
if err != nil {
return err
}

// premine initial validators
for _, v := range initialValidators {
allocs[v.Address] = &chain.GenesisAccount{
Balance: v.Balance,
}
}

// premine other accounts
for _, premine := range premineBalances {
// validators have already been premined, so no need to premine them again
Expand Down Expand Up @@ -231,7 +227,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
}
}

genesisExtraData, err := generateExtraDataPolyBft(validatorMetadata)
genesisExtraData, err := GenerateExtraDataPolyBft(validatorMetadata)
if err != nil {
return err
}
Expand Down Expand Up @@ -310,8 +306,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
return helper.WriteGenesisConfigToDisk(chainConfig, params.genesisPath)
}

func (p *genesisParams) deployContracts(totalStake *big.Int,
rewardTokenByteCode []byte,
func (p *genesisParams) deployContracts(rewardTokenByteCode []byte,
polybftConfig *polybft.PolyBFTConfig) (map[types.Address]*chain.GenesisAccount, error) {
type contractInfo struct {
artifact *artifact.Artifact
Expand Down Expand Up @@ -477,33 +472,10 @@ func (p *genesisParams) deployContracts(totalStake *big.Int,
return allocations, nil
}

// generateExtraDataPolyBft populates Extra with specific fields required for polybft consensus protocol
func generateExtraDataPolyBft(validators []*validator.ValidatorMetadata) ([]byte, error) {
delta := &validator.ValidatorSetDelta{
Added: validators,
Removed: bitmap.Bitmap{},
}

extra := polybft.Extra{Validators: delta, Checkpoint: &polybft.CheckpointData{}}

return extra.MarshalRLPTo(nil), nil
}

// getValidatorAccounts gathers validator accounts info either from CLI or from provided local storage
func (p *genesisParams) getValidatorAccounts(
premineBalances map[types.Address]*premineInfo) ([]*validator.GenesisValidator, error) {
// populate validators premine info
stakeMap := make(map[types.Address]*premineInfo, len(p.stakes))

for _, stake := range p.stakes {
stakeInfo, err := parsePremineInfo(stake)
if err != nil {
return nil, fmt.Errorf("invalid stake amount provided '%s' : %w", stake, err)
}

stakeMap[stakeInfo.address] = stakeInfo
}

if len(p.validators) > 0 {
validators := make([]*validator.GenesisValidator, len(p.validators))
for i, val := range p.validators {
Expand Down Expand Up @@ -533,8 +505,8 @@ func (p *genesisParams) getValidatorAccounts(
MultiAddr: parts[0],
Address: addr,
BlsKey: trimmedBLSKey,
Balance: getPremineAmount(addr, premineBalances, command.DefaultPremineBalance),
Stake: getPremineAmount(addr, stakeMap, command.DefaultStake),
Balance: big.NewInt(0),
Stake: big.NewInt(0),
}
}

Expand All @@ -552,8 +524,8 @@ func (p *genesisParams) getValidatorAccounts(
}

for _, v := range validators {
v.Balance = getPremineAmount(v.Address, premineBalances, command.DefaultPremineBalance)
v.Stake = getPremineAmount(v.Address, stakeMap, command.DefaultStake)
v.Balance = big.NewInt(0)
v.Stake = big.NewInt(0)
}

return validators, nil
Expand Down
14 changes: 14 additions & 0 deletions command/genesis/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"strings"

"github.com/0xPolygon/polygon-edge/command"
"github.com/0xPolygon/polygon-edge/consensus/polybft"
"github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap"
"github.com/0xPolygon/polygon-edge/consensus/polybft/validator"
"github.com/0xPolygon/polygon-edge/consensus/polybft/wallet"
"github.com/0xPolygon/polygon-edge/secrets"
Expand Down Expand Up @@ -228,3 +230,15 @@ func getSecrets(directory string) (*wallet.Account, string, error) {

return account, nodeID, err
}

// GenerateExtraDataPolyBft populates Extra with specific fields required for polybft consensus protocol
func GenerateExtraDataPolyBft(validators []*validator.ValidatorMetadata) ([]byte, error) {
delta := &validator.ValidatorSetDelta{
Added: validators,
Removed: bitmap.Bitmap{},
}

extra := polybft.Extra{Validators: delta, Checkpoint: &polybft.CheckpointData{}}

return extra.MarshalRLPTo(nil), nil
}
58 changes: 0 additions & 58 deletions command/rootchain/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"math/big"

"github.com/spf13/cobra"
"github.com/umbracle/ethgo"
Expand Down Expand Up @@ -636,24 +635,6 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
return nil, 0, err
}

// initialize CheckpointManager
validatorSet, err := validatorSetToABISlice(outputter, initialValidators)
if err != nil {
return nil, 0, fmt.Errorf("failed to convert validators to map: %w", err)
}

initParams := &contractsapi.InitializeCheckpointManagerFn{
ChainID_: big.NewInt(chainID),
NewBls: rootchainConfig.BLSAddress,
NewBn256G2: rootchainConfig.BN256G2Address,
NewValidatorSet: validatorSet,
}

if err := initContract(outputter, txRelayer, initParams,
rootchainConfig.CheckpointManagerAddress, checkpointManagerName, deployerKey); err != nil {
return nil, 0, err
}

return rootchainConfig, supernetID, nil
}

Expand Down Expand Up @@ -749,42 +730,3 @@ func initContract(cmdOutput command.OutputFormatter, txRelayer txrelayer.TxRelay

return nil
}

// validatorSetToABISlice converts given validators to generic map
// which is used for ABI encoding validator set being sent to the rootchain contract
func validatorSetToABISlice(o command.OutputFormatter,
validators []*validator.GenesisValidator) ([]*contractsapi.Validator, error) {
accSet := make(validator.AccountSet, len(validators))

if _, err := o.Write([]byte(fmt.Sprintf("%s [VALIDATORS]\n", contractsDeploymentTitle))); err != nil {
return nil, err
}

for i, val := range validators {
if _, err := o.Write([]byte(fmt.Sprintf("%v\n", val))); err != nil {
return nil, err
}

blsKey, err := val.UnmarshalBLSPublicKey()
if err != nil {
return nil, err
}

accSet[i] = &validator.ValidatorMetadata{
Address: val.Address,
BlsKey: blsKey,
VotingPower: new(big.Int).Set(val.Stake),
}
}

hash, err := accSet.Hash()
if err != nil {
return nil, err
}

if _, err := o.Write([]byte(fmt.Sprintf("%s Validators hash: %s\n", contractsDeploymentTitle, hash))); err != nil {
return nil, err
}

return accSet.ToAPIBinding(), nil
}
4 changes: 2 additions & 2 deletions command/rootchain/staking/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (sp *stakeParams) validateFlags() (err error) {

type stakeResult struct {
validatorAddress string
amount uint64
amount *big.Int
}

func (sr stakeResult) GetOutput() string {
Expand All @@ -48,7 +48,7 @@ func (sr stakeResult) GetOutput() string {

vals := make([]string, 0, 2)
vals = append(vals, fmt.Sprintf("Validator Address|%s", sr.validatorAddress))
vals = append(vals, fmt.Sprintf("Amount Staked|%v", sr.amount))
vals = append(vals, fmt.Sprintf("Amount Staked|%d", sr.amount))

buffer.WriteString(helper.FormatKV(vals))
buffer.WriteString("\n")
Expand Down
2 changes: 1 addition & 1 deletion command/rootchain/staking/stake.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ func runCommand(cmd *cobra.Command, _ []string) error {
continue
}

result.amount = stakeAddedEvent.Amount.Uint64()
result.amount = stakeAddedEvent.Amount
result.validatorAddress = stakeAddedEvent.Validator.String()
foundLog = true

Expand Down
Loading

0 comments on commit 470ffb8

Please sign in to comment.