Skip to content

Commit

Permalink
Small fixes for e2e tests
Browse files Browse the repository at this point in the history
  • Loading branch information
goran-ethernal committed Nov 29, 2023
1 parent c702e13 commit 65cbf8f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 127 deletions.
35 changes: 17 additions & 18 deletions e2e-polybft/e2e/consensus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,16 +289,15 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) {

func TestE2E_Consensus_Validator_Unstake(t *testing.T) {
var (
premineAmount = ethgo.Ether(10)
stakeAmount = ethgo.Ether(100)
)

cluster := framework.NewTestCluster(t, 5,
framework.WithEpochReward(int(ethgo.Ether(1).Uint64())),
framework.WithEpochSize(5),
framework.WithSecretsCallback(func(addresses []types.Address, config *framework.TestClusterConfig) {
for _, a := range addresses {
config.Premine = append(config.Premine, fmt.Sprintf("%s:%d", a, premineAmount))
config.StakeAmounts = append(config.StakeAmounts, new(big.Int).Set(premineAmount))
for range addresses {
config.StakeAmounts = append(config.StakeAmounts, new(big.Int).Set(stakeAmount))
}
}),
)
Expand Down Expand Up @@ -379,6 +378,10 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {

validatorsAddrs := make([]types.Address, validatorCount)
initValidatorsBalance := ethgo.Ether(1)
initMinterBalance := ethgo.Ether(100000)

minter, err := wallet.GenerateKey()
require.NoError(t, err)

// because we are using native token as reward wallet, and it has default premine balance
initialTotalSupply := new(big.Int).Set(command.DefaultPremineBalance)
Expand All @@ -387,8 +390,12 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {
validatorCount,
framework.WithNativeTokenConfig(
fmt.Sprintf("%s:%s:%d", tokenName, tokenSymbol, decimals)),
framework.WithBladeAdmin(minter.Address().String()),
framework.WithEpochSize(epochSize),
framework.WithSecretsCallback(func(addrs []types.Address, config *framework.TestClusterConfig) {
config.Premine = append(config.Premine, fmt.Sprintf("%s:%d", minter.Address(), initMinterBalance))
initialTotalSupply.Add(initialTotalSupply, initMinterBalance)

for i, addr := range addrs {
config.Premine = append(config.Premine, fmt.Sprintf("%s:%d", addr, initValidatorsBalance))
config.StakeAmounts = append(config.StakeAmounts, new(big.Int).Set(initValidatorsBalance))
Expand All @@ -402,9 +409,6 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {

cluster.WaitForReady(t)

nativeTokenAdmin, err := validatorHelper.GetAccountFromDir(cluster.Servers[0].DataDir())
require.NoError(t, err)

// initialize tx relayer
relayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(targetJSONRPC))
require.NoError(t, err)
Expand Down Expand Up @@ -435,9 +439,9 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {

// make sure minter account can mint tokens
for _, addr := range validatorsAddrs {
balance, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
require.NoError(t, err)
t.Logf("Pre-mint balance: %v=%d\n", addr, balance)
t.Logf("Pre-mint balance: %v=%d\n", addr, balanceBefore)

mintInput, err := mintFn.Encode([]interface{}{addr, mintAmount})
require.NoError(t, err)
Expand All @@ -447,22 +451,17 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) {
To: &nativeTokenAddr,
Input: mintInput,
Type: ethgo.TransactionDynamicFee,
}, nativeTokenAdmin.Ecdsa)
}, minter)
require.NoError(t, err)
require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status)

balance, err = targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(addr), ethgo.Latest)
require.NoError(t, err)

t.Logf("Post-mint balance: %v=%d\n", addr, balance)
require.Equal(t, new(big.Int).Add(initValidatorsBalance, mintAmount), balance)
t.Logf("Post-mint balance: %v=%d\n", addr, balanceAfter)
require.True(t, balanceAfter.Cmp(new(big.Int).Add(mintAmount, balanceBefore)) >= 0)
}

// assert that minter balance remained the same
minterBalance, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(nativeTokenAdmin.Address()), ethgo.Latest)
require.NoError(t, err)
require.Equal(t, initValidatorsBalance, minterBalance)

// try sending mint transaction from non minter account and make sure it would fail
nonMinterAcc, err := validatorHelper.GetAccountFromDir(cluster.Servers[1].DataDir())
require.NoError(t, err)
Expand Down
108 changes: 0 additions & 108 deletions e2e-polybft/framework/test-bridge.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
package framework

import (
"context"
"errors"
"fmt"
"math/big"
"path"
"strconv"
"strings"
"testing"
"time"

"golang.org/x/sync/errgroup"

"github.com/0xPolygon/polygon-edge/command"
bridgeCommon "github.com/0xPolygon/polygon-edge/command/bridge/common"
bridgeHelper "github.com/0xPolygon/polygon-edge/command/bridge/helper"
"github.com/0xPolygon/polygon-edge/command/bridge/server"
"github.com/0xPolygon/polygon-edge/command/genesis"
cmdHelper "github.com/0xPolygon/polygon-edge/command/helper"
Expand Down Expand Up @@ -370,109 +365,6 @@ func (t *TestBridge) fundAddressesOnRoot(tokenConfig *polybft.TokenConfig, polyb
return nil
}

func (t *TestBridge) whitelistValidators(validatorAddresses []types.Address,
polybftConfig polybft.PolyBFTConfig) error {
addressesAsString := make([]string, len(validatorAddresses))
for i := 0; i < len(validatorAddresses); i++ {
addressesAsString[i] = validatorAddresses[i].String()
}

args := []string{
"validator",
"whitelist-validators",
"--addresses", strings.Join(addressesAsString, ","),
"--jsonrpc", t.JSONRPCAddr(),
"--private-key", bridgeHelper.TestAccountPrivKey,
}

if err := t.cmdRun(args...); err != nil {
return fmt.Errorf("failed to whitelist genesis validators on supernet manager: %w", err)
}

return nil
}

func (t *TestBridge) registerGenesisValidators(polybftConfig polybft.PolyBFTConfig) error {
validatorSecrets, err := genesis.GetValidatorKeyFiles(t.clusterConfig.TmpDir, t.clusterConfig.ValidatorPrefix)
if err != nil {
return fmt.Errorf("could not get validator secrets on whitelist of genesis validators: %w", err)
}

g, ctx := errgroup.WithContext(context.Background())

for _, secret := range validatorSecrets {
secret := secret

g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
default:
args := []string{
"validator",
"register-validator",
"--jsonrpc", t.JSONRPCAddr(),
"--" + polybftsecrets.AccountDirFlag, path.Join(t.clusterConfig.TmpDir, secret),
}

if err := t.cmdRun(args...); err != nil {
return fmt.Errorf("failed to register genesis validator on supernet manager: %w", err)
}

return nil
}
})
}

return g.Wait()
}

func (t *TestBridge) initialStakingOfGenesisValidators(polybftConfig polybft.PolyBFTConfig) error {
validatorSecrets, err := genesis.GetValidatorKeyFiles(t.clusterConfig.TmpDir, t.clusterConfig.ValidatorPrefix)
if err != nil {
return fmt.Errorf("could not get validator secrets on initial staking of genesis validators: %w", err)
}

g, ctx := errgroup.WithContext(context.Background())

for i, secret := range validatorSecrets {
secret := secret
i := i

g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
default:
args := []string{
"validator",
"stake",
"--jsonrpc", t.JSONRPCAddr(),
"--" + polybftsecrets.AccountDirFlag, path.Join(t.clusterConfig.TmpDir, secret),
"--amount", t.getStakeAmount(i).String(),
}

if err := t.cmdRun(args...); err != nil {
return fmt.Errorf("failed to do initial staking for genesis validator on stake manager: %w", err)
}

return nil
}
})
}

return g.Wait()
}

func (t *TestBridge) getStakeAmount(validatorIndex int) *big.Int {
l := len(t.clusterConfig.StakeAmounts)
if l == 0 || l <= validatorIndex {
return command.DefaultStake
}

return t.clusterConfig.StakeAmounts[validatorIndex]
}

// FundValidators sends tokens to a rootchain validators
func (t *TestBridge) FundValidators(secretsPaths []string, amounts []*big.Int) error {
if len(secretsPaths) != len(amounts) {
Expand Down
31 changes: 30 additions & 1 deletion e2e-polybft/framework/test-cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"testing"
"time"

"github.com/0xPolygon/polygon-edge/command"
"github.com/0xPolygon/polygon-edge/command/genesis"
"github.com/0xPolygon/polygon-edge/consensus/polybft"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
Expand Down Expand Up @@ -110,6 +111,7 @@ type TestClusterConfig struct {
EpochReward int
NativeTokenConfigRaw string
SecretsCallback func([]types.Address, *TestClusterConfig)
BladeAdmin string

ContractDeployerAllowListAdmin []types.Address
ContractDeployerAllowListEnabled []types.Address
Expand Down Expand Up @@ -399,6 +401,12 @@ func WithProxyContractsAdmin(address string) ClusterOption {
}
}

func WithBladeAdmin(address string) ClusterOption {
return func(h *TestClusterConfig) {
h.BladeAdmin = address
}
}

func isTrueEnv(e string) bool {
return strings.ToLower(os.Getenv(e)) == "true"
}
Expand Down Expand Up @@ -494,9 +502,15 @@ func NewTestCluster(t *testing.T, validatorsCount int, opts ...ClusterOption) *T
"--premine", "0x0000000000000000000000000000000000000000",
"--reward-wallet", testRewardWalletAddr.String(),
"--trieroot", cluster.Config.InitialStateRoot.String(),
"--blade-admin", addresses[0].String(), // we put first validator as owner by default
}

bladeAdmin := cluster.Config.BladeAdmin
if cluster.Config.BladeAdmin == "" {
bladeAdmin = addresses[0].String()
}

args = append(args, "--blade-admin", bladeAdmin)

if cluster.Config.BlockTime != 0 {
args = append(args, "--block-time",
cluster.Config.BlockTime.String())
Expand All @@ -520,6 +534,12 @@ func NewTestCluster(t *testing.T, validatorsCount int, opts ...ClusterOption) *T
args = append(args, "--premine", premine)
}

if len(cluster.Config.StakeAmounts) > 0 {
for i, addr := range addresses {
args = append(args, "--stake", fmt.Sprintf("%s:%s", addr.String(), cluster.getStakeAmount(i).String()))
}
}

validators, err := genesis.ReadValidatorsByPrefix(
cluster.Config.TmpDir, cluster.Config.ValidatorPrefix, nil)
require.NoError(t, err)
Expand Down Expand Up @@ -795,6 +815,15 @@ func (c *TestCluster) getOpenPort() int64 {
return c.initialPort
}

func (c *TestCluster) getStakeAmount(validatorIndex int) *big.Int {
l := len(c.Config.StakeAmounts)
if l == 0 || l <= validatorIndex || validatorIndex < 0 {
return command.DefaultStake
}

return c.Config.StakeAmounts[validatorIndex]
}

// runCommand executes command with given arguments
func runCommand(binary string, args []string, stdout io.Writer) error {
var stdErr bytes.Buffer
Expand Down

0 comments on commit 65cbf8f

Please sign in to comment.