Skip to content

Commit

Permalink
apply patch
Browse files Browse the repository at this point in the history
  • Loading branch information
dusannosovic-ethernal committed Nov 7, 2023
1 parent de0f009 commit edf2af9
Show file tree
Hide file tree
Showing 37 changed files with 772 additions and 1,050 deletions.
10 changes: 10 additions & 0 deletions command/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ func setFlags(cmd *cobra.Command) {
),
)

cmd.Flags().StringArrayVar(
&params.stake,
stakeFlag,
[]string{},
fmt.Sprintf(
"the staked accounts and balances (format: <address>[:<balance>]). Default staked balance: %d",
command.DefaultStake,
),
)

cmd.Flags().Uint64Var(
&params.blockGasLimit,
blockGasLimitFlag,
Expand Down
22 changes: 22 additions & 0 deletions command/genesis/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const (
dirFlag = "dir"
nameFlag = "name"
premineFlag = "premine"
stakeFlag = "stake"
chainIDFlag = "chain-id"
epochSizeFlag = "epoch-size"
epochRewardFlag = "epoch-reward"
Expand Down Expand Up @@ -71,6 +72,7 @@ type genesisParams struct {
name string
consensusRaw string
premine []string
stake []string
bootnodes []string

chainID uint64
Expand Down Expand Up @@ -128,6 +130,7 @@ type genesisParams struct {
nativeTokenConfig *polybft.TokenConfig

premineInfos []*helper.PremineInfo
stakeInfos map[types.Address]*big.Int

// rewards
rewardTokenCode string
Expand Down Expand Up @@ -159,6 +162,10 @@ func (p *genesisParams) validateFlags() error {
return err
}

if err := p.parseStakeInfo(); err != nil {
return err
}

if p.isPolyBFTConsensus() {
if err := p.extractNativeTokenMetadata(); err != nil {
return err
Expand Down Expand Up @@ -519,6 +526,21 @@ func (p *genesisParams) parsePremineInfo() error {
return nil
}

func (p *genesisParams) parseStakeInfo() error {
p.stakeInfos = make(map[types.Address]*big.Int, len(p.stake))

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

p.stakeInfos[stakeInfo.Address] = stakeInfo.Amount
}

return nil
}

// validatePremineInfo validates whether reserve account (0x0 address) is premined
func (p *genesisParams) validatePremineInfo() error {
for _, premineInfo := range p.premineInfos {
Expand Down
9 changes: 6 additions & 3 deletions command/genesis/polybft_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,10 @@ func (p *genesisParams) deployContracts(
artifact: contractsapi.RewardPool,
address: contracts.RewardPoolContractV1,
},
{
artifact: contractsapi.StakeManager,
address: contracts.StakeManagerContract,
},
}

if !params.nativeTokenConfig.IsMintable {
Expand Down Expand Up @@ -528,7 +532,7 @@ func (p *genesisParams) getValidatorAccounts() ([]*validator.GenesisValidator, e
MultiAddr: parts[0],
Address: addr,
BlsKey: trimmedBLSKey,
Stake: big.NewInt(0),
Stake: p.stakeInfos[addr],
}
}

Expand All @@ -540,11 +544,10 @@ func (p *genesisParams) getValidatorAccounts() ([]*validator.GenesisValidator, e
validatorsPath = path.Dir(p.genesisPath)
}

validators, err := ReadValidatorsByPrefix(validatorsPath, p.validatorsPrefixPath)
validators, err := ReadValidatorsByPrefixStakeInfos(validatorsPath, p.validatorsPrefixPath, p.stakeInfos)
if err != nil {
return nil, err
}

return validators, nil

Check failure on line 551 in command/genesis/polybft_params.go

View workflow job for this annotation

GitHub Actions / golangci_lint

return statements should not be cuddled if block has more than two lines (wsl)

Check failure on line 551 in command/genesis/polybft_params.go

View workflow job for this annotation

GitHub Actions / golangci_lint

return statements should not be cuddled if block has more than two lines (wsl)
}

Expand Down
28 changes: 28 additions & 0 deletions command/genesis/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,34 @@ func ReadValidatorsByPrefix(dir, prefix string) ([]*validator.GenesisValidator,
return validators, nil
}

// ReadValidatorsByPrefix reads validators secrets on a given root directory and with given folder prefix
func ReadValidatorsByPrefixStakeInfos(dir, prefix string, stakeInfos map[types.Address]*big.Int) ([]*validator.GenesisValidator, error) {

Check failure on line 250 in command/genesis/utils.go

View workflow job for this annotation

GitHub Actions / golangci_lint

line is 137 characters (lll)

Check failure on line 250 in command/genesis/utils.go

View workflow job for this annotation

GitHub Actions / golangci_lint

line is 137 characters (lll)
validatorKeyFiles, err := GetValidatorKeyFiles(dir, prefix)
if err != nil {
return nil, err
}

validators := make([]*validator.GenesisValidator, len(validatorKeyFiles))

for i, file := range validatorKeyFiles {
path := filepath.Join(dir, file)

account, nodeID, err := getSecrets(path)
if err != nil {
return nil, err
}

validators[i] = &validator.GenesisValidator{
Address: types.Address(account.Ecdsa.Address()),
BlsKey: hex.EncodeToString(account.Bls.PublicKey().Marshal()),
MultiAddr: fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", "127.0.0.1", bootnodePortStart+int64(i), nodeID),
Stake: stakeInfos[types.Address(account.Ecdsa.Address())],
}
}

return validators, nil
}

func getSecrets(directory string) (*wallet.Account, string, error) {
baseConfig := &secrets.SecretsManagerParams{
Logger: hclog.NewNullLogger(),
Expand Down
8 changes: 2 additions & 6 deletions command/polybft/polybft_command.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package polybft

import (
"github.com/0xPolygon/polygon-edge/command/rootchain/registration"
"github.com/0xPolygon/polygon-edge/command/rootchain/staking"
"github.com/0xPolygon/polygon-edge/command/rootchain/supernet"
"github.com/0xPolygon/polygon-edge/command/rootchain/supernet/stakemanager"
"github.com/0xPolygon/polygon-edge/command/rootchain/validators"
"github.com/0xPolygon/polygon-edge/command/rootchain/whitelist"
"github.com/0xPolygon/polygon-edge/command/rootchain/withdraw"
"github.com/0xPolygon/polygon-edge/command/sidechain/registration"
"github.com/0xPolygon/polygon-edge/command/sidechain/rewards"
"github.com/0xPolygon/polygon-edge/command/sidechain/staking"
"github.com/0xPolygon/polygon-edge/command/sidechain/unstaking"
sidechainWithdraw "github.com/0xPolygon/polygon-edge/command/sidechain/withdraw"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -37,9 +36,6 @@ func GetCommand() *cobra.Command {
registration.GetCommand(),
// rootchain (stake manager) stake command
staking.GetCommand(),
// rootchain (supernet manager) command for finalizing genesis
// validator set and enabling staking
supernet.GetCommand(),
// rootchain command for deploying stake manager
stakemanager.GetCommand(),
)
Expand Down
56 changes: 14 additions & 42 deletions command/rootchain/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package deploy

import (
"context"
"errors"
"fmt"
"sync"

Expand All @@ -18,7 +17,6 @@ import (
"github.com/0xPolygon/polygon-edge/consensus/polybft"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi/artifact"
"github.com/0xPolygon/polygon-edge/consensus/polybft/signer"
"github.com/0xPolygon/polygon-edge/consensus/polybft/validator"
"github.com/0xPolygon/polygon-edge/contracts"
"github.com/0xPolygon/polygon-edge/txrelayer"
Expand Down Expand Up @@ -114,24 +112,6 @@ var (
// initializersMap maps rootchain contract names to initializer function callbacks
initializersMap = map[string]func(command.OutputFormatter, txrelayer.TxRelayer,
*polybft.RootchainConfig, ethgo.Key) error{
getProxyNameForImpl(customSupernetManagerName): func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeCustomSupernetManagerFn{
NewStakeManager: config.StakeManagerAddress,
NewBls: config.BLSAddress,
NewStateSender: config.StateSenderAddress,
NewMatic: types.StringToAddress(params.stakeTokenAddr),
NewChildValidatorSet: contracts.ValidatorSetContract,
NewExitHelper: config.ExitHelperAddress,
NewDomain: signer.DomainValidatorSetString,
NewRootERC20Predicate: config.RootERC20PredicateAddress,
}

return initContract(fmt, relayer, initParams,
config.CustomSupernetManagerAddress, customSupernetManagerName, key)
},
getProxyNameForImpl(exitHelperName): func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
Expand Down Expand Up @@ -234,7 +214,6 @@ var (

type deploymentResultInfo struct {
RootchainCfg *polybft.RootchainConfig
SupernetID int64
CommandResults []command.CommandResult
}

Expand Down Expand Up @@ -386,7 +365,6 @@ func runCommand(cmd *cobra.Command, _ []string) {
consensusCfg.Bridge.EventTrackerStartBlocks = map[types.Address]uint64{
deploymentResultInfo.RootchainCfg.StateSenderAddress: blockNum,
}
consensusCfg.SupernetID = deploymentResultInfo.SupernetID

// write updated consensus configuration
chainConfig.Params.Engine[polybft.ConsensusName] = consensusCfg
Expand All @@ -409,13 +387,13 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
initialValidators []*validator.GenesisValidator, cmdCtx context.Context) (deploymentResultInfo, error) {
txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(client), txrelayer.WithWriter(outputter))
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil},
return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil},
fmt.Errorf("failed to initialize tx relayer: %w", err)
}

deployerKey, err := helper.DecodePrivateKey(params.deployerKey)
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil},
return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil},
fmt.Errorf("failed to initialize deployer key: %w", err)
}

Expand All @@ -424,7 +402,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,

txn := helper.CreateTransaction(ethgo.ZeroAddress, &deployerAddr, nil, ethgo.Ether(1), true)
if _, err = txRelayer.SendTransactionLocal(txn); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil}, err
}
}

Expand All @@ -449,7 +427,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
// use existing root chain ERC20 token
if err := populateExistingTokenAddr(client.Eth(),
params.rootERC20TokenAddr, rootERC20Name, rootchainConfig); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil}, err
}
} else {
// deploy MockERC20 as a root chain root native token
Expand Down Expand Up @@ -537,11 +515,6 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
name: erc1155TemplateName,
artifact: contractsapi.ChildERC1155,
},
{
name: customSupernetManagerName,
artifact: contractsapi.CustomSupernetManager,
hasProxy: true,
},
}

allContracts = append(tokenContracts, allContracts...)
Expand Down Expand Up @@ -655,18 +628,17 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client,
}

if err := g.Wait(); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil}, err
}

// register supernets manager on stake manager
supernetID, err := registerChainOnStakeManager(txRelayer, rootchainConfig, deployerKey)
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}

/* supernetID, err := registerChainOnStakeManager(txRelayer, rootchainConfig, deployerKey)
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}
*/
return deploymentResultInfo{
RootchainCfg: rootchainConfig,
SupernetID: supernetID,
CommandResults: commandResults}, nil
}

Expand Down Expand Up @@ -694,7 +666,7 @@ func populateExistingTokenAddr(eth *jsonrpc.Eth, tokenAddr, tokenName string,
}

// registerChainOnStakeManager registers child chain and its supernet manager on rootchain
func registerChainOnStakeManager(txRelayer txrelayer.TxRelayer,
/* func registerChainOnStakeManager(txRelayer txrelayer.TxRelayer,
rootchainCfg *polybft.RootchainConfig, deployerKey ethgo.Key) (int64, error) {
registerChainFn := &contractsapi.RegisterChildChainStakeManagerFn{
Manager: rootchainCfg.CustomSupernetManagerAddress,
Expand Down Expand Up @@ -738,7 +710,7 @@ func registerChainOnStakeManager(txRelayer txrelayer.TxRelayer,
}
return supernetID, nil
}
} */

// initContract initializes arbitrary contract with given parameters deployed on a given address
func initContract(cmdOutput command.OutputFormatter, txRelayer txrelayer.TxRelayer,
Expand Down Expand Up @@ -778,8 +750,8 @@ func collectResultsOnError(results map[string]*deployContractResult) deploymentR
commandResults = append([]command.CommandResult{messageResult}, commandResults...)

return deploymentResultInfo{
RootchainCfg: nil,
SupernetID: 0,
RootchainCfg: nil,

CommandResults: commandResults}
}

Expand Down
5 changes: 2 additions & 3 deletions command/rootchain/helper/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ func GetECDSAKey(privateKey, accountDir, accountConfig string) (ethgo.Key, error
// GetValidatorInfo queries SupernetManager smart contract on root
// and retrieves validator info for given address
func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeManagerAddr types.Address,
chainID int64, txRelayer txrelayer.TxRelayer) (*polybft.ValidatorInfo, error) {
txRelayer txrelayer.TxRelayer) (*polybft.ValidatorInfo, error) {
caller := ethgo.Address(contracts.SystemCaller)
getValidatorMethod := contractsapi.CustomSupernetManager.Abi.GetMethod("getValidator")
getValidatorMethod := contractsapi.StakeManager.Abi.GetMethod("stakeOf")

encode, err := getValidatorMethod.Encode([]interface{}{validatorAddr})
if err != nil {
Expand Down Expand Up @@ -201,7 +201,6 @@ func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeMan
}

stakeOfFn := &contractsapi.StakeOfStakeManagerFn{
ID: new(big.Int).SetInt64(chainID),
Validator: types.Address(validatorAddr),
}

Expand Down
23 changes: 0 additions & 23 deletions command/rootchain/premine/premine.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ import (
"github.com/0xPolygon/polygon-edge/command/polybftsecrets"
rootHelper "github.com/0xPolygon/polygon-edge/command/rootchain/helper"
sidechainHelper "github.com/0xPolygon/polygon-edge/command/sidechain"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/txrelayer"
"github.com/0xPolygon/polygon-edge/types"
"github.com/spf13/cobra"
"github.com/umbracle/ethgo"
)

var (
Expand Down Expand Up @@ -128,27 +126,6 @@ func runCommand(cmd *cobra.Command, _ []string) error {
return fmt.Errorf("approve transaction failed on block %d", receipt.BlockNumber)
}

premineFn := &contractsapi.AddGenesisBalanceCustomSupernetManagerFn{
Amount: params.amountValue,
}

premineInput, err := premineFn.EncodeAbi()
if err != nil {
return err
}

supernetManagerAddr := ethgo.Address(types.StringToAddress(params.customSupernetManager))
txn := rootHelper.CreateTransaction(ownerKey.Address(), &supernetManagerAddr, premineInput, nil, true)

receipt, err = txRelayer.SendTransaction(txn, ownerKey)
if err != nil {
return err
}

if receipt == nil || receipt.Status == uint64(types.ReceiptFailed) {
return fmt.Errorf("premine transaction failed on block %d", receipt.BlockNumber)
}

outputter.WriteCommandResult(&premineResult{
Address: ownerKey.Address().String(),
Amount: params.amountValue,
Expand Down
Loading

0 comments on commit edf2af9

Please sign in to comment.