Skip to content

Commit

Permalink
Add stake flag to manifest command (#1137)
Browse files Browse the repository at this point in the history
* Add stake flag to manifest command

* Resolve TODO

* Minor fixes

* Convert stake flag into string array

* Change DefaultPremineBalance to big.Int
  • Loading branch information
Stefan-Ethernal authored Mar 22, 2023
1 parent 308fe5b commit 983ef2d
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 39 deletions.
11 changes: 9 additions & 2 deletions command/default.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
package command

import "github.com/0xPolygon/polygon-edge/server"
import (
"github.com/0xPolygon/polygon-edge/server"
"github.com/umbracle/ethgo"
)

const (
DefaultGenesisFileName = "genesis.json"
DefaultChainName = "polygon-edge"
DefaultChainID = 100
DefaultPremineBalance = "0xD3C21BCECCEDA1000000" // 1 million units of native network currency
DefaultConsensus = server.PolyBFTConsensus
DefaultGenesisGasUsed = 458752 // 0x70000
DefaultGenesisGasLimit = 5242880 // 0x500000
)

var (
DefaultStake = ethgo.Ether(1e6)
DefaultPremineBalance = ethgo.Ether(1e6)
)

const (
JSONOutputFlag = "json"
GRPCAddressFlag = "grpc-address"
Expand Down
2 changes: 1 addition & 1 deletion command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func setFlags(cmd *cobra.Command) {
premineFlag,
[]string{},
fmt.Sprintf(
"the premined accounts and balances (format: <address>:<balance>). Default premined balance: %s",
"the premined accounts and balances (format: <address>:<balance>). Default premined balance: %d",
command.DefaultPremineBalance,
),
)
Expand Down
2 changes: 1 addition & 1 deletion command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ func (p *genesisParams) initGenesisConfig() error {
}

chainConfig.Genesis.Alloc[premineInfo.Address] = &chain.GenesisAccount{
Balance: premineInfo.Balance,
Balance: premineInfo.Amount,
}
}

Expand Down
5 changes: 2 additions & 3 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,8 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
// populate premine info for validator accounts
genesisValidators[validator.Address] = struct{}{}

// TODO: @Stefan-Ethernal change this to Stake when https://github.com/0xPolygon/polygon-edge/pull/1137 gets merged
// increment total stake
totalStake.Add(totalStake, validator.Balance)
totalStake.Add(totalStake, validator.Stake)
}

// deploy genesis contracts
Expand Down Expand Up @@ -162,7 +161,7 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
// premine non-validator accounts
for _, premine := range premineInfos {
allocs[premine.Address] = &chain.GenesisAccount{
Balance: premine.Balance,
Balance: premine.Amount,
}
}

Expand Down
23 changes: 13 additions & 10 deletions command/genesis/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,30 +64,33 @@ func verifyGenesisExistence(genesisPath string) *GenesisGenError {

type PremineInfo struct {
Address types.Address
Balance *big.Int
Amount *big.Int
}

// ParsePremineInfo parses provided premine information and returns premine address and premine balance
// ParsePremineInfo parses provided premine information and returns premine address and amount
func ParsePremineInfo(premineInfoRaw string) (*PremineInfo, error) {
var (
address types.Address
val = command.DefaultPremineBalance
amount = command.DefaultPremineBalance
err error
)

if delimiterIdx := strings.Index(premineInfoRaw, ":"); delimiterIdx != -1 {
// <addr>:<balance>
address, val = types.StringToAddress(premineInfoRaw[:delimiterIdx]), premineInfoRaw[delimiterIdx+1:]
valueRaw := premineInfoRaw[delimiterIdx+1:]

amount, err = types.ParseUint256orHex(&valueRaw)
if err != nil {
return nil, fmt.Errorf("failed to parse amount %s: %w", valueRaw, err)
}

address = types.StringToAddress(premineInfoRaw[:delimiterIdx])
} else {
// <addr>
address = types.StringToAddress(premineInfoRaw)
}

amount, err := types.ParseUint256orHex(&val)
if err != nil {
return nil, fmt.Errorf("failed to parse amount %s: %w", val, err)
}

return &PremineInfo{Address: address, Balance: amount}, nil
return &PremineInfo{Address: address, Amount: amount}, nil
}

// parseTrackerStartBlocks parses provided event tracker start blocks configuration.
Expand Down
43 changes: 29 additions & 14 deletions command/polybftmanifest/manifest_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
const (
manifestPathFlag = "path"
premineValidatorsFlag = "premine-validators"
stakeFlag = "stake"
validatorsFlag = "validators"
validatorsPathFlag = "validators-path"
validatorsPrefixFlag = "validators-prefix"
Expand Down Expand Up @@ -88,7 +89,7 @@ func setFlags(cmd *cobra.Command) {
premineValidatorsFlag,
[]string{},
fmt.Sprintf(
"the premined validators and balances (format: <address>:<balance>). Default premined balance: %s",
"the premined validators and balances (format: <address>[:<balance>]). Default premined balance: %d",
command.DefaultPremineBalance,
),
)
Expand All @@ -100,6 +101,16 @@ func setFlags(cmd *cobra.Command) {
"the ID of the chain",
)

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 Expand Up @@ -130,6 +141,7 @@ type manifestInitParams struct {
validatorsPath string
validatorsPrefixPath string
premineValidators []string
stakes []string
validators []string
chainID int64
}
Expand All @@ -146,6 +158,7 @@ func (p *manifestInitParams) validateFlags() error {
func (p *manifestInitParams) getValidatorAccounts() ([]*polybft.Validator, error) {
// populate validators premine info
premineMap := make(map[types.Address]*genesis.PremineInfo, len(p.premineValidators))
stakeMap := make(map[types.Address]*genesis.PremineInfo, len(p.stakes))

for _, premine := range p.premineValidators {
premineInfo, err := genesis.ParsePremineInfo(premine)
Expand All @@ -156,12 +169,13 @@ func (p *manifestInitParams) getValidatorAccounts() ([]*polybft.Validator, error
premineMap[premineInfo.Address] = premineInfo
}

// parse default validators' balance
defaultBalanceRaw := command.DefaultPremineBalance
for _, stake := range p.stakes {
stakeInfo, err := genesis.ParsePremineInfo(stake)
if err != nil {
return nil, fmt.Errorf("invalid stake amount provided '%s' : %w", stake, err)
}

defaultBalance, err := types.ParseUint256orHex(&defaultBalanceRaw)
if err != nil {
return nil, fmt.Errorf("provided invalid premine validators balance: %s", defaultBalanceRaw)
stakeMap[stakeInfo.Address] = stakeInfo
}

if len(p.validators) > 0 {
Expand Down Expand Up @@ -198,7 +212,8 @@ func (p *manifestInitParams) getValidatorAccounts() ([]*polybft.Validator, error
Address: addr,
BlsKey: trimmedBLSKey,
BlsSignature: parts[3],
Balance: getBalance(addr, premineMap, defaultBalance),
Balance: getPremineAmount(addr, premineMap, command.DefaultPremineBalance),
Stake: getPremineAmount(addr, stakeMap, command.DefaultStake),
}
}

Expand All @@ -216,21 +231,21 @@ func (p *manifestInitParams) getValidatorAccounts() ([]*polybft.Validator, error
}

for _, v := range validators {
v.Balance = getBalance(v.Address, premineMap, defaultBalance)
v.Balance = getPremineAmount(v.Address, premineMap, command.DefaultPremineBalance)
v.Stake = getPremineAmount(v.Address, stakeMap, command.DefaultStake)
}

return validators, nil
}

// getBalance retrieves balance from the premine map or if not provided, returns default balance
func getBalance(addr types.Address, premineMap map[types.Address]*genesis.PremineInfo,
defaultBalance *big.Int) *big.Int {
balance := defaultBalance
// getPremineAmount retrieves amount from the premine map or if not provided, returns default amount
func getPremineAmount(addr types.Address, premineMap map[types.Address]*genesis.PremineInfo,
defaultAmount *big.Int) *big.Int {
if premine, exists := premineMap[addr]; exists {
balance = premine.Balance
return premine.Amount
}

return balance
return defaultAmount
}

func (p *manifestInitParams) getResult() command.CommandResult {
Expand Down
4 changes: 2 additions & 2 deletions command/rootchain/initcontracts/init_contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
// fund account
deployerAddress := deployerKey.Address()

txn := &ethgo.Transaction{To: &deployerAddress, Value: ethgo.Ether(1e6)}
txn := &ethgo.Transaction{To: &deployerAddress, Value: command.DefaultPremineBalance}
if _, err := txRelayer.SendTransactionLocal(txn); err != nil {
return err
}
Expand Down Expand Up @@ -463,7 +463,7 @@ func validatorSetToABISlice(o command.OutputFormatter,
accSet[i] = &polybft.ValidatorMetadata{
Address: validator.Address,
BlsKey: blsKey,
VotingPower: new(big.Int).Set(validator.Balance),
VotingPower: new(big.Int).Set(validator.Stake),
}
}

Expand Down
1 change: 1 addition & 0 deletions consensus/polybft/mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ func (v *testValidator) paramsValidator() *Validator {
Address: v.Address(),
BlsKey: hex.EncodeToString(bls),
Balance: big.NewInt(1000),
Stake: big.NewInt(1000),
}
}

Expand Down
19 changes: 14 additions & 5 deletions consensus/polybft/polybft_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ type Validator struct {
BlsKey string
BlsSignature string
Balance *big.Int
Stake *big.Int
MultiAddr string
}

Expand All @@ -92,20 +93,23 @@ type validatorRaw struct {
BlsKey string `json:"blsKey"`
BlsSignature string `json:"blsSignature"`
Balance *string `json:"balance"`
Stake *string `json:"stake"`
MultiAddr string `json:"multiAddr"`
}

func (v *Validator) MarshalJSON() ([]byte, error) {
raw := &validatorRaw{Address: v.Address, BlsKey: v.BlsKey, MultiAddr: v.MultiAddr, BlsSignature: v.BlsSignature}
raw.Balance = types.EncodeBigInt(v.Balance)
raw.Stake = types.EncodeBigInt(v.Stake)

return json.Marshal(raw)
}

func (v *Validator) UnmarshalJSON(data []byte) error {
var raw validatorRaw

var err error
var (
raw validatorRaw
err error
)

if err = json.Unmarshal(data, &raw); err != nil {
return err
Expand All @@ -115,8 +119,13 @@ func (v *Validator) UnmarshalJSON(data []byte) error {
v.BlsKey = raw.BlsKey
v.BlsSignature = raw.BlsSignature
v.MultiAddr = raw.MultiAddr

v.Balance, err = types.ParseUint256orHex(raw.Balance)
if err != nil {
return err
}

v.Stake, err = types.ParseUint256orHex(raw.Stake)
if err != nil {
return err
}
Expand Down Expand Up @@ -165,7 +174,7 @@ func (v Validator) ToValidatorInitAPIBinding() (*contractsapi.ValidatorInit, err
Addr: v.Address,
Pubkey: pubKey.ToBigInt(),
Signature: signBigInts,
Stake: new(big.Int).Set(v.Balance),
Stake: new(big.Int).Set(v.Stake),
}, nil
}

Expand All @@ -179,7 +188,7 @@ func (v *Validator) ToValidatorMetadata() (*ValidatorMetadata, error) {
metadata := &ValidatorMetadata{
Address: v.Address,
BlsKey: blsKey,
VotingPower: new(big.Int).Set(v.Balance),
VotingPower: new(big.Int).Set(v.Stake),
}

return metadata, nil
Expand Down
1 change: 1 addition & 0 deletions consensus/polybft/sc_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ func TestIntegration_CommitEpoch(t *testing.T) {
initValidators[i] = &Validator{
Address: validator.Address,
Balance: validator.VotingPower,
Stake: validator.VotingPower,
BlsKey: hex.EncodeToString(validator.BlsKey.Marshal()),
BlsSignature: hex.EncodeToString(signatureBytes),
}
Expand Down
2 changes: 2 additions & 0 deletions e2e-polybft/e2e/consensus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ func TestE2E_Consensus_Delegation_Undelegation(t *testing.T) {
framework.WithSecretsCallback(func(addresses []types.Address, config *framework.TestClusterConfig) {
for _, a := range addresses {
config.PremineValidators = append(config.PremineValidators, fmt.Sprintf("%s:%s", a, premineBalance))
config.StakeAmounts = append(config.StakeAmounts, fmt.Sprintf("%s:%s", a, premineBalance))
}
}),
)
Expand Down Expand Up @@ -442,6 +443,7 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) {
framework.WithSecretsCallback(func(addresses []types.Address, config *framework.TestClusterConfig) {
for _, a := range addresses {
config.PremineValidators = append(config.PremineValidators, fmt.Sprintf("%s:%d", a, premineAmount))
config.StakeAmounts = append(config.StakeAmounts, fmt.Sprintf("%s:%d", a, premineAmount))
}
}),
)
Expand Down
8 changes: 7 additions & 1 deletion e2e-polybft/framework/test-cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ type TestClusterConfig struct {

Name string
Premine []string // address[:amount]
PremineValidators []string // address:[amount]
PremineValidators []string // address[:amount]
StakeAmounts []string // address[:amount]
HasBridge bool
BootnodeCount int
NonValidatorCount int
Expand Down Expand Up @@ -266,6 +267,7 @@ func NewTestCluster(t *testing.T, validatorsCount int, opts ...ClusterOption) *T
EpochReward: 1,
BlockGasLimit: 1e7, // 10M
PremineValidators: []string{},
StakeAmounts: []string{},
}

if config.ValidatorPrefix == "" {
Expand Down Expand Up @@ -319,6 +321,10 @@ func NewTestCluster(t *testing.T, validatorsCount int, opts ...ClusterOption) *T
args = append(args, "--premine-validators", premineValidator)
}

for _, validatorStake := range cluster.Config.StakeAmounts {
args = append(args, "--stake", validatorStake)
}

// run manifest file creation
require.NoError(t, cluster.cmdRun(args...))

Expand Down

0 comments on commit 983ef2d

Please sign in to comment.