Skip to content

Commit

Permalink
Populate voting power on checkpoint manager initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan-Ethernal committed Nov 24, 2022
1 parent b39447c commit b22d230
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 28 deletions.
10 changes: 10 additions & 0 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,13 @@ func importChain(content []byte) (*Chain, error) {

return chain, nil
}

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

return big.NewInt(0)
}
19 changes: 5 additions & 14 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ const (
defaultPolyBftValidatorPrefixPath = "test-chain-"
defaultBridge = false

bootnodePortStart = 30301
defaultStakeBalance = 100
bootnodePortStart = 30301

WeiScalingFactor = int64(1e18) // 10^18
)

func (p *genesisParams) generatePolyBFTConfig() (*chain.Chain, error) {
Expand Down Expand Up @@ -143,7 +144,7 @@ func (p *genesisParams) getGenesisValidators(validators []GenesisTarget,
result = append(result, &polybft.Validator{
Address: addr,
BlsKey: parts[1],
Balance: getBalance(addr, allocs),
Balance: chain.GetGenesisAccountBalance(addr, allocs),
})
}
} else {
Expand All @@ -153,24 +154,14 @@ func (p *genesisParams) getGenesisValidators(validators []GenesisTarget,
result = append(result, &polybft.Validator{
Address: addr,
BlsKey: hex.EncodeToString(pubKeyMarshalled),
Balance: getBalance(addr, allocs),
Balance: chain.GetGenesisAccountBalance(addr, allocs),
})
}
}

return result
}

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

return big.NewInt(defaultStakeBalance)
}

func (p *genesisParams) generatePolyBftGenesis() error {
config, err := params.generatePolyBFTConfig()
if err != nil {
Expand Down
12 changes: 6 additions & 6 deletions command/rootchain/helper/txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func GetRootchainAdminKey() ethgo.Key {
// SendTxn function sends transaction to the rootchain
// blocks until receipt hash is returned
func SendTxn(nonce uint64, txn *ethgo.Transaction, key ethgo.Key) (*ethgo.Receipt, error) {
provider, err := getJSONRPCClient()
provider, err := GetJSONRPCClient()
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -90,7 +90,7 @@ func SendTxn(nonce uint64, txn *ethgo.Transaction, key ethgo.Key) (*ethgo.Receip

// Call function is used to query a smart contract on given 'to' address
func Call(from, to ethgo.Address, input []byte) (string, error) {
provider, err := getJSONRPCClient()
provider, err := GetJSONRPCClient()
if err != nil {
return "", err
}
Expand All @@ -107,7 +107,7 @@ func Call(from, to ethgo.Address, input []byte) (string, error) {
}

func ExistsCode(addr types.Address) (bool, error) {
provider, err := getJSONRPCClient()
provider, err := GetJSONRPCClient()
if err != nil {
return false, err
}
Expand All @@ -121,7 +121,7 @@ func ExistsCode(addr types.Address) (bool, error) {
}

func GetPendingNonce(addr types.Address) (uint64, error) {
provider, err := getJSONRPCClient()
provider, err := GetJSONRPCClient()
if err != nil {
return 0, err
}
Expand All @@ -135,7 +135,7 @@ func GetPendingNonce(addr types.Address) (uint64, error) {
}

func FundAccount(account types.Address) (types.Hash, error) {
provider, err := getJSONRPCClient()
provider, err := GetJSONRPCClient()
if err != nil {
return types.Hash{}, err
}
Expand Down Expand Up @@ -167,7 +167,7 @@ func FundAccount(account types.Address) (types.Hash, error) {
return types.BytesToHash(receipt.TransactionHash.Bytes()), nil
}

func getJSONRPCClient() (*jsonrpc.Client, error) {
func GetJSONRPCClient() (*jsonrpc.Client, error) {
jrpcClientLock.Lock()
defer jrpcClientLock.Unlock()

Expand Down
52 changes: 45 additions & 7 deletions command/rootchain/initcontracts/init_contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io/ioutil"
"math/big"
"os"
"path"
"path/filepath"
"strings"
Expand All @@ -14,6 +15,7 @@ import (
"github.com/umbracle/ethgo"
"github.com/umbracle/ethgo/abi"

"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/command"
"github.com/0xPolygon/polygon-edge/command/genesis"
"github.com/0xPolygon/polygon-edge/command/rootchain/helper"
Expand Down Expand Up @@ -75,6 +77,12 @@ func setFlags(cmd *cobra.Command) {
defaultValidatorPrefixPath,
"Validators prefix path",
)
cmd.Flags().StringVar(
&params.genesisPath,
genesisPathFlag,
defaultGenesisPath,
"Genesis configuration path",
)
}

func runPreRun(_ *cobra.Command, _ []string) error {
Expand Down Expand Up @@ -102,7 +110,7 @@ func runCommand(cmd *cobra.Command, _ []string) {
}

if err := deployContracts(outputter); err != nil {
outputter.SetError(fmt.Errorf("failed to deploy: %w", err))
outputter.SetError(fmt.Errorf("failed to deploy rootchain contracts: %w", err))

return
}
Expand All @@ -113,6 +121,25 @@ func runCommand(cmd *cobra.Command, _ []string) {
})
}

func getGenesisAlloc() (map[types.Address]*chain.GenesisAccount, error) {
genesisFile, err := os.Open(params.genesisPath)
if err != nil {
return nil, fmt.Errorf("failed to open genesis config file: %w", err)
}

genesisRaw, err := ioutil.ReadAll(genesisFile)
if err != nil {
return nil, fmt.Errorf("failed to read genesis config file: %w", err)
}

var chain *chain.Chain
if err := json.Unmarshal(genesisRaw, &chain); err != nil {
return nil, fmt.Errorf("failed to unmarshal genesis configuration: %w", err)
}

return chain.Genesis.Alloc, nil
}

func deployContracts(outputter command.OutputFormatter) error {
// if the bridge contract is not created, we have to deploy all the contracts
// fund account
Expand Down Expand Up @@ -191,8 +218,12 @@ func deployContracts(outputter command.OutputFormatter) error {

// initializeCheckpointManager invokes initialize function on CheckpointManager smart contract
func initializeCheckpointManager(nonce uint64) error {
validatorSetMap, err := validatorSetToABISlice()
allocs, err := getGenesisAlloc()
if err != nil {
return err
}

validatorSetMap, err := validatorSetToABISlice(allocs)
initCheckpointInput, err := initCheckpointManager.Encode(
[]interface{}{
helper.BLSAddress,
Expand Down Expand Up @@ -224,19 +255,20 @@ func initializeCheckpointManager(nonce uint64) error {
}

// initializeCheckpointManager invokes initialize function on CheckpointManager smart contract
func validatorSetToABISlice() ([]map[string]interface{}, error) {
func validatorSetToABISlice(allocs map[types.Address]*chain.GenesisAccount) ([]map[string]interface{}, error) {
validatorsInfo, err := genesis.ReadValidatorsByRegexp(path.Dir(params.validatorPath), params.validatorPrefixPath)
if err != nil {
return nil, err
}

validatorSetMap := make([]map[string]interface{}, len(validatorsInfo))

for i, valid := range validatorsInfo {
for i, validatorInfo := range validatorsInfo {
addr := types.Address(validatorInfo.Account.Ecdsa.Address())
validatorSetMap[i] = map[string]interface{}{
"_address": types.Address(valid.Account.Ecdsa.Address()),
"blsKey": valid.Account.Bls.PublicKey().ToBigInt(),
"votingPower": 1, // TODO - get voting power
"_address": addr,
"blsKey": validatorInfo.Account.Bls.PublicKey().ToBigInt(),
"votingPower": convertWeiToTokensAmount(chain.GetGenesisAccountBalance(addr, allocs)),
}
}

Expand Down Expand Up @@ -268,3 +300,9 @@ func readContractBytecode(rootPath, contractPath, contractName string) ([]byte,

return hex.MustDecodeHex(artifact.Bytecode), nil
}

// TODO: Use the one from the polybft_params
// convertWeiToTokensAmount converts provided wei balance to tokens amount
func convertWeiToTokensAmount(weiBalance *big.Int) *big.Int {
return weiBalance.Div(weiBalance, big.NewInt(genesis.WeiScalingFactor))
}
23 changes: 22 additions & 1 deletion command/rootchain/initcontracts/params.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
package initcontracts

import (
"errors"
"fmt"
"os"
)

const (
contractsPathFlag = "path"
validatorPrefixPathFlag = "validator-prefix"
validatorPathFlag = "validator-path"
genesisPathFlag = "genesis-path"

defaultValidatorPrefixPath = "test-chain-"
defaultValidatorPath = "./"
defaultGenesisPath = "./genesis.json"
)

type initContractsParams struct {
contractsPath string
validatorPrefixPath string
validatorPath string
genesisPath string
}

func (ep *initContractsParams) validateFlags() error {
func (ip *initContractsParams) validateFlags() error {
if _, err := os.Stat(ip.contractsPath); errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("provided smart contracts directory '%s' doesn't exist", ip.contractsPath)
}

if _, err := os.Stat(ip.validatorPath); errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("provided validators data directory '%s' doesn't exist", ip.validatorPath)
}

if _, err := os.Stat(ip.genesisPath); errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("provided genesis path '%s' doesn't exist", ip.genesisPath)
}

return nil
}
1 change: 1 addition & 0 deletions consensus/polybft/fsm.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ func (f *fsm) Validate(proposal []byte) error {
}

f.logger.Debug("[FSM Validate]", "signed hash", checkpointHash.String())
f.logger.Info("[FSM Validate]", "signed hash raw", checkpointHash.Bytes())

// validate header fields
if err := validateHeaderFields(f.parent, block.Header); err != nil {
Expand Down

0 comments on commit b22d230

Please sign in to comment.