Skip to content

Commit

Permalink
Merge premine-validators with premine flag in genesis command
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan-Ethernal committed Apr 14, 2023
1 parent 536c58d commit 8efb934
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 145 deletions.
10 changes: 0 additions & 10 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,13 +361,3 @@ func importChain(content []byte) (*Chain, error) {

return chain, nil
}

// GetGenesisAccountBalance returns balance for genesis account based on its address (expressed in weis).
// If not found in provided allocations map, 0 is returned.
func GetGenesisAccountBalance(address types.Address, allocations map[types.Address]*GenesisAccount) (*big.Int, error) {
if genesisAcc, ok := allocations[address]; ok {
return genesisAcc.Balance, nil
}

return nil, fmt.Errorf("genesis account %s is not found among genesis allocations", address)
}
47 changes: 0 additions & 47 deletions chain/chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ package chain

import (
"encoding/json"
"fmt"
"math/big"
"reflect"
"testing"

"github.com/0xPolygon/polygon-edge/types"
"github.com/stretchr/testify/require"
)

var emptyAddr types.Address
Expand Down Expand Up @@ -152,48 +150,3 @@ func TestGenesisX(t *testing.T) {
})
}
}

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

testAddr := types.Address{0x2}
cases := []struct {
name string
address types.Address
allocs map[types.Address]*GenesisAccount
expectedBalance *big.Int
shouldFail bool
}{
{
name: "Query existing account",
address: testAddr,
allocs: map[types.Address]*GenesisAccount{
testAddr: {Balance: big.NewInt(50)},
},
expectedBalance: big.NewInt(50),
shouldFail: false,
},
{
name: "Query non-existing account",
address: testAddr,
allocs: nil,
expectedBalance: nil,
shouldFail: true,
},
}

for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()

actualBalance, err := GetGenesisAccountBalance(c.address, c.allocs)
if c.shouldFail {
require.Equal(t, err.Error(), fmt.Errorf("genesis account %s is not found among genesis allocations", c.address).Error())
} else {
require.NoError(t, err)
}
require.Equal(t, c.expectedBalance, actualBalance)
})
}
}
12 changes: 1 addition & 11 deletions 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: %d",
"the premined accounts and balances (format: <address>[:<balance>]). Default premined balance: %d",
command.DefaultPremineBalance,
),
)
Expand Down Expand Up @@ -170,16 +170,6 @@ func setFlags(cmd *cobra.Command) {
"validators defined by user (format: <P2P multi address>:<ECDSA address>:<public BLS key>:<BLS signature>)",
)

cmd.Flags().StringArrayVar(
&params.premineValidators,
premineValidatorsFlag,
[]string{},
fmt.Sprintf(
"the premined validators and balances (format: <address>[:<balance>]). Default premined balance: %d",
command.DefaultPremineBalance,
),
)

cmd.Flags().StringArrayVar(
&params.stakes,
stakeFlag,
Expand Down
7 changes: 3 additions & 4 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ type genesisParams struct {
// PolyBFT
validatorsPath string
validatorsPrefixPath string
premineValidators []string
stakes []string
validators []string
sprintSize uint64
Expand Down Expand Up @@ -372,13 +371,13 @@ func (p *genesisParams) initGenesisConfig() error {
}

for _, premineRaw := range p.premine {
premineInfo, err := ParsePremineInfo(premineRaw)
premineInfo, err := parsePremineInfo(premineRaw)
if err != nil {
return err
}

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

Expand Down
97 changes: 30 additions & 67 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,10 @@ import (
)

const (
premineValidatorsFlag = "premine-validators"
stakeFlag = "stake"
validatorsFlag = "validators"
validatorsPathFlag = "validators-path"
validatorsPrefixFlag = "validators-prefix"
stakeFlag = "stake"
validatorsFlag = "validators"
validatorsPathFlag = "validators-path"
validatorsPrefixFlag = "validators-prefix"

defaultValidatorPrefixPath = "test-chain-"

Expand Down Expand Up @@ -63,7 +62,19 @@ var (

// generatePolyBftChainConfig creates and persists polybft chain configuration to the provided file path
func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) error {
initialValidators, err := p.getValidatorAccounts()
// populate premine balance map
premineBalances := make(map[types.Address]*premineInfo, len(p.premine))

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

premineBalances[premineInfo.address] = premineInfo
}

initialValidators, err := p.getValidatorAccounts(premineBalances)
if err != nil {
return fmt.Errorf("failed to retrieve genesis validators: %w", err)
}
Expand Down Expand Up @@ -138,55 +149,16 @@ func (p *genesisParams) generatePolyBftChainConfig(o command.OutputFormatter) er
return err
}

premineInfos := make([]*PremineInfo, len(p.premine))
premineValidatorsAddrs := []string{}
// premine non-validator
for i, premine := range p.premine {
premineInfo, err := ParsePremineInfo(premine)
if err != nil {
return err
}

// collect validators addresses which got premined, as it is an error
// genesis validators balances must be defined in manifest file and should not be changed in the genesis
if _, ok := genesisValidators[premineInfo.Address]; ok {
premineValidatorsAddrs = append(premineValidatorsAddrs, premineInfo.Address.String())
} else {
premineInfos[i] = premineInfo
}
}

// if there are any premined validators in the genesis command, consider it as an error
if len(premineValidatorsAddrs) > 0 {
return fmt.Errorf("it is not allowed to override genesis validators balance outside from the manifest definition. "+
"Validators which got premined: (%s)", strings.Join(premineValidatorsAddrs, ", "))
}

// populate genesis validators balances
for _, validator := range initialValidators {
allocs[validator.Address] = &chain.GenesisAccount{
Balance: validator.Balance,
}
}

// premine non-validator accounts
for _, premine := range premineInfos {
allocs[premine.Address] = &chain.GenesisAccount{
Balance: premine.Amount,
// premine accounts
for _, premine := range premineBalances {
allocs[premine.address] = &chain.GenesisAccount{
Balance: premine.amount,
}
}

validatorMetadata := make([]*polybft.ValidatorMetadata, len(initialValidators))

for i, validator := range initialValidators {
// update balance of genesis validator, because it could be changed via premine flag
balance, err := chain.GetGenesisAccountBalance(validator.Address, allocs)
if err != nil {
return err
}

validator.Balance = balance

// create validator metadata instance
metadata, err := validator.ToValidatorMetadata()
if err != nil {
Expand Down Expand Up @@ -337,27 +309,18 @@ func generateExtraDataPolyBft(validators []*polybft.ValidatorMetadata) ([]byte,
}

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

for _, premine := range p.premineValidators {
premineInfo, err := ParsePremineInfo(premine)
if err != nil {
return nil, fmt.Errorf("invalid balance amount provided '%s' : %w", premine, err)
}

premineMap[premineInfo.Address] = premineInfo
}
stakeMap := make(map[types.Address]*premineInfo, len(p.stakes))

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

stakeMap[stakeInfo.Address] = stakeInfo
stakeMap[stakeInfo.address] = stakeInfo
}

if len(p.validators) > 0 {
Expand Down Expand Up @@ -394,7 +357,7 @@ func (p *genesisParams) getValidatorAccounts() ([]*polybft.Validator, error) {
Address: addr,
BlsKey: trimmedBLSKey,
BlsSignature: parts[3],
Balance: getPremineAmount(addr, premineMap, command.DefaultPremineBalance),
Balance: getPremineAmount(addr, premineBalances, command.DefaultPremineBalance),
Stake: getPremineAmount(addr, stakeMap, command.DefaultStake),
}
}
Expand All @@ -413,18 +376,18 @@ func (p *genesisParams) getValidatorAccounts() ([]*polybft.Validator, error) {
}

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

return validators, nil
}

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

return defaultAmount
Expand Down
12 changes: 6 additions & 6 deletions command/genesis/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ func verifyGenesisExistence(genesisPath string) *GenesisGenError {
return nil
}

type PremineInfo struct {
Address types.Address
Amount *big.Int
type premineInfo struct {
address types.Address
amount *big.Int
}

// ParsePremineInfo parses provided premine information and returns premine address and amount
func ParsePremineInfo(premineInfoRaw string) (*PremineInfo, error) {
// parsePremineInfo parses provided premine information and returns premine address and amount
func parsePremineInfo(premineInfoRaw string) (*premineInfo, error) {
var (
address types.Address
amount = command.DefaultPremineBalance
Expand All @@ -90,7 +90,7 @@ func ParsePremineInfo(premineInfoRaw string) (*PremineInfo, error) {
address = types.StringToAddress(premineInfoRaw)
}

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

// parseTrackerStartBlocks parses provided event tracker start blocks configuration.
Expand Down

0 comments on commit 8efb934

Please sign in to comment.