Skip to content

Commit

Permalink
Merge pull request #6221 from multiversx/update-feat-chain-simulator-…
Browse files Browse the repository at this point in the history
…30.05

Update feat chain simulator 30.05
miiu96 authored May 30, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents 256f000 + 31cfe98 commit 19b1685
Showing 13 changed files with 525 additions and 474 deletions.
45 changes: 45 additions & 0 deletions integrationTests/chainSimulator/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package chainSimulator

import (
"math/big"

"github.com/multiversx/mx-chain-go/node/chainSimulator/configs"

"github.com/multiversx/mx-chain-core-go/data/transaction"
)

const (
minGasPrice = 1000000000
txVersion = 1
mockTxSignature = "sig"

// OkReturnCode the const for the ok return code
OkReturnCode = "ok"
)

var (
// ZeroValue the variable for the zero big int
ZeroValue = big.NewInt(0)
// OneEGLD the variable for one egld value
OneEGLD = big.NewInt(1000000000000000000)
// MinimumStakeValue the variable for the minimum stake value
MinimumStakeValue = big.NewInt(0).Mul(OneEGLD, big.NewInt(2500))
// InitialAmount the variable for initial minting amount in account
InitialAmount = big.NewInt(0).Mul(OneEGLD, big.NewInt(100))
)

// GenerateTransaction will generate a transaction based on input data
func GenerateTransaction(sender []byte, nonce uint64, receiver []byte, value *big.Int, data string, gasLimit uint64) *transaction.Transaction {
return &transaction.Transaction{
Nonce: nonce,
Value: value,
SndAddr: sender,
RcvAddr: receiver,
Data: []byte(data),
GasLimit: gasLimit,
GasPrice: minGasPrice,
ChainID: []byte(configs.ChainID),
Version: txVersion,
Signature: []byte(mockTxSignature),
}
}
8 changes: 6 additions & 2 deletions integrationTests/chainSimulator/interface.go
Original file line number Diff line number Diff line change
@@ -3,11 +3,12 @@ package chainSimulator
import (
"math/big"

"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
"github.com/multiversx/mx-chain-go/node/chainSimulator/process"

"github.com/multiversx/mx-chain-core-go/data/api"
"github.com/multiversx/mx-chain-core-go/data/transaction"
crypto "github.com/multiversx/mx-chain-crypto-go"
"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
"github.com/multiversx/mx-chain-go/node/chainSimulator/process"
)

// ChainSimulator defines the operations for an entity that can simulate operations of a chain
@@ -16,6 +17,7 @@ type ChainSimulator interface {
GenerateBlocksUntilEpochIsReached(targetEpoch int32) error
AddValidatorKeys(validatorsPrivateKeys [][]byte) error
GetNodeHandler(shardID uint32) process.NodeHandler
RemoveAccounts(addresses []string) error
SendTxAndGenerateBlockTilTxIsExecuted(txToSend *transaction.Transaction, maxNumOfBlockToGenerateWhenExecutingTx int) (*transaction.ApiTransactionResult, error)
SendTxsAndGenerateBlocksTilAreExecuted(txsToSend []*transaction.Transaction, maxNumOfBlocksToGenerateWhenExecutingTx int) ([]*transaction.ApiTransactionResult, error)
SetStateMultiple(stateSlice []*dtos.AddressState) error
@@ -24,4 +26,6 @@ type ChainSimulator interface {
GetAccount(address dtos.WalletAddress) (api.AccountResponse, error)
ForceResetValidatorStatisticsCache() error
GetValidatorPrivateKeys() []crypto.PrivateKey
SetKeyValueForAddress(address string, keyValueMap map[string]string) error
Close()
}
39 changes: 5 additions & 34 deletions integrationTests/chainSimulator/staking/common.go
Original file line number Diff line number Diff line change
@@ -5,24 +5,17 @@ import (
"math/big"
"testing"

"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/data/transaction"
chainSimulatorIntegrationTests "github.com/multiversx/mx-chain-go/integrationTests/chainSimulator"
"github.com/multiversx/mx-chain-go/node/chainSimulator/configs"
"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
chainSimulatorProcess "github.com/multiversx/mx-chain-go/node/chainSimulator/process"
"github.com/multiversx/mx-chain-go/process"
"github.com/multiversx/mx-chain-go/vm"

"github.com/multiversx/mx-chain-core-go/core"
"github.com/stretchr/testify/require"
)

const (
minGasPrice = 1000000000
txVersion = 1
mockTxSignature = "sig"

// OkReturnCode the const for the ok return code
OkReturnCode = "ok"
// MockBLSSignature the const for a mocked bls signature
MockBLSSignature = "010101"
// GasLimitForStakeOperation the const for the gas limit value for the stake operation
@@ -45,14 +38,8 @@ const (
)

var (
// ZeroValue the variable for the zero big int
ZeroValue = big.NewInt(0)
// OneEGLD the variable for one egld value
OneEGLD = big.NewInt(1000000000000000000)
//InitialDelegationValue the variable for the initial delegation value
InitialDelegationValue = big.NewInt(0).Mul(OneEGLD, big.NewInt(1250))
// MinimumStakeValue the variable for the minimum stake value
MinimumStakeValue = big.NewInt(0).Mul(OneEGLD, big.NewInt(2500))
InitialDelegationValue = big.NewInt(0).Mul(chainSimulatorIntegrationTests.OneEGLD, big.NewInt(1250))
)

// GetNonce will return the nonce of the provided address
@@ -63,22 +50,6 @@ func GetNonce(t *testing.T, cs chainSimulatorIntegrationTests.ChainSimulator, ad
return account.Nonce
}

// GenerateTransaction will generate a transaction based on input data
func GenerateTransaction(sender []byte, nonce uint64, receiver []byte, value *big.Int, data string, gasLimit uint64) *transaction.Transaction {
return &transaction.Transaction{
Nonce: nonce,
Value: value,
SndAddr: sender,
RcvAddr: receiver,
Data: []byte(data),
GasLimit: gasLimit,
GasPrice: minGasPrice,
ChainID: []byte(configs.ChainID),
Version: txVersion,
Signature: []byte(mockTxSignature),
}
}

// GetBLSKeyStatus will return the bls key status
func GetBLSKeyStatus(t *testing.T, metachainNode chainSimulatorProcess.NodeHandler, blsKey []byte) string {
scQuery := &process.SCQuery{
@@ -90,7 +61,7 @@ func GetBLSKeyStatus(t *testing.T, metachainNode chainSimulatorProcess.NodeHandl
}
result, _, err := metachainNode.GetFacadeHandler().ExecuteSCQuery(scQuery)
require.Nil(t, err)
require.Equal(t, OkReturnCode, result.ReturnCode)
require.Equal(t, chainSimulatorIntegrationTests.OkReturnCode, result.ReturnCode)

return string(result.ReturnData[0])
}
@@ -105,7 +76,7 @@ func GetAllNodeStates(t *testing.T, metachainNode chainSimulatorProcess.NodeHand
}
result, _, err := metachainNode.GetFacadeHandler().ExecuteSCQuery(scQuery)
require.Nil(t, err)
require.Equal(t, OkReturnCode, result.ReturnCode)
require.Equal(t, chainSimulatorIntegrationTests.OkReturnCode, result.ReturnCode)

m := make(map[string]string)
status := ""
15 changes: 8 additions & 7 deletions integrationTests/chainSimulator/staking/jail/jail_test.go
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ import (

"github.com/multiversx/mx-chain-go/common"
"github.com/multiversx/mx-chain-go/config"
chainSimulatorIntegrationTests "github.com/multiversx/mx-chain-go/integrationTests/chainSimulator"
"github.com/multiversx/mx-chain-go/integrationTests/chainSimulator/staking"
"github.com/multiversx/mx-chain-go/node/chainSimulator"
"github.com/multiversx/mx-chain-go/node/chainSimulator/components/api"
@@ -96,12 +97,12 @@ func testChainSimulatorJailAndUnJail(t *testing.T, targetEpoch int32, nodeStatus
_, blsKeys, err := chainSimulator.GenerateBlsPrivateKeys(1)
require.Nil(t, err)

mintValue := big.NewInt(0).Mul(staking.OneEGLD, big.NewInt(3000))
mintValue := big.NewInt(0).Mul(chainSimulatorIntegrationTests.OneEGLD, big.NewInt(3000))
walletAddress, err := cs.GenerateAndMintWalletAddress(core.AllShardId, mintValue)
require.Nil(t, err)

txDataField := fmt.Sprintf("stake@01@%s@%s", blsKeys[0], staking.MockBLSSignature)
txStake := staking.GenerateTransaction(walletAddress.Bytes, 0, vm.ValidatorSCAddress, staking.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
txStake := chainSimulatorIntegrationTests.GenerateTransaction(walletAddress.Bytes, 0, vm.ValidatorSCAddress, chainSimulatorIntegrationTests.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
stakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, stakeTx)
@@ -117,7 +118,7 @@ func testChainSimulatorJailAndUnJail(t *testing.T, targetEpoch int32, nodeStatus
// do an unjail transaction
unJailValue, _ := big.NewInt(0).SetString("2500000000000000000", 10)
txUnJailDataField := fmt.Sprintf("unJail@%s", blsKeys[0])
txUnJail := staking.GenerateTransaction(walletAddress.Bytes, 1, vm.ValidatorSCAddress, unJailValue, txUnJailDataField, staking.GasLimitForStakeOperation)
txUnJail := chainSimulatorIntegrationTests.GenerateTransaction(walletAddress.Bytes, 1, vm.ValidatorSCAddress, unJailValue, txUnJailDataField, staking.GasLimitForStakeOperation)

err = cs.GenerateBlocksUntilEpochIsReached(targetEpoch)
require.Nil(t, err)
@@ -202,12 +203,12 @@ func TestChainSimulator_FromQueueToAuctionList(t *testing.T) {
err = cs.AddValidatorKeys([][]byte{privateKeys[1]})
require.Nil(t, err)

mintValue := big.NewInt(0).Mul(staking.OneEGLD, big.NewInt(6000))
mintValue := big.NewInt(0).Mul(chainSimulatorIntegrationTests.OneEGLD, big.NewInt(6000))
walletAddress, err := cs.GenerateAndMintWalletAddress(core.AllShardId, mintValue)
require.Nil(t, err)

txDataField := fmt.Sprintf("stake@01@%s@%s", blsKeys[0], staking.MockBLSSignature)
txStake := staking.GenerateTransaction(walletAddress.Bytes, 0, vm.ValidatorSCAddress, staking.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
txStake := chainSimulatorIntegrationTests.GenerateTransaction(walletAddress.Bytes, 0, vm.ValidatorSCAddress, chainSimulatorIntegrationTests.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
stakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, stakeTx)
@@ -222,7 +223,7 @@ func TestChainSimulator_FromQueueToAuctionList(t *testing.T) {

// add one more node
txDataField = fmt.Sprintf("stake@01@%s@%s", blsKeys[1], staking.MockBLSSignature)
txStake = staking.GenerateTransaction(walletAddress.Bytes, 1, vm.ValidatorSCAddress, staking.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
txStake = chainSimulatorIntegrationTests.GenerateTransaction(walletAddress.Bytes, 1, vm.ValidatorSCAddress, chainSimulatorIntegrationTests.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
stakeTx, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(txStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, stakeTx)
@@ -234,7 +235,7 @@ func TestChainSimulator_FromQueueToAuctionList(t *testing.T) {
// unJail the first node
unJailValue, _ := big.NewInt(0).SetString("2500000000000000000", 10)
txUnJailDataField := fmt.Sprintf("unJail@%s", blsKeys[0])
txUnJail := staking.GenerateTransaction(walletAddress.Bytes, 2, vm.ValidatorSCAddress, unJailValue, txUnJailDataField, staking.GasLimitForStakeOperation)
txUnJail := chainSimulatorIntegrationTests.GenerateTransaction(walletAddress.Bytes, 2, vm.ValidatorSCAddress, unJailValue, txUnJailDataField, staking.GasLimitForStakeOperation)

unJailTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txUnJail, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
27 changes: 14 additions & 13 deletions integrationTests/chainSimulator/staking/stake/simpleStake_test.go
Original file line number Diff line number Diff line change
@@ -7,18 +7,19 @@ import (
"testing"
"time"

"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/data/transaction"
"github.com/stretchr/testify/require"

"github.com/multiversx/mx-chain-go/common"
"github.com/multiversx/mx-chain-go/config"
chainSimulatorIntegrationTests "github.com/multiversx/mx-chain-go/integrationTests/chainSimulator"
"github.com/multiversx/mx-chain-go/integrationTests/chainSimulator/staking"
"github.com/multiversx/mx-chain-go/node/chainSimulator"
"github.com/multiversx/mx-chain-go/node/chainSimulator/components/api"
"github.com/multiversx/mx-chain-go/node/chainSimulator/configs"
"github.com/multiversx/mx-chain-go/node/chainSimulator/process"
"github.com/multiversx/mx-chain-go/vm"

"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/data/transaction"
"github.com/stretchr/testify/require"
)

// Test scenarios
@@ -87,7 +88,7 @@ func testChainSimulatorSimpleStake(t *testing.T, targetEpoch int32, nodesStatus
require.NotNil(t, cs)
defer cs.Close()

mintValue := big.NewInt(0).Mul(staking.OneEGLD, big.NewInt(3000))
mintValue := big.NewInt(0).Mul(chainSimulatorIntegrationTests.OneEGLD, big.NewInt(3000))
wallet1, err := cs.GenerateAndMintWalletAddress(0, mintValue)
require.Nil(t, err)
wallet2, err := cs.GenerateAndMintWalletAddress(0, mintValue)
@@ -102,15 +103,15 @@ func testChainSimulatorSimpleStake(t *testing.T, targetEpoch int32, nodesStatus
require.Nil(t, err)

dataFieldTx1 := fmt.Sprintf("stake@01@%s@%s", blsKeys[0], staking.MockBLSSignature)
tx1Value := big.NewInt(0).Mul(big.NewInt(2499), staking.OneEGLD)
tx1 := staking.GenerateTransaction(wallet1.Bytes, 0, vm.ValidatorSCAddress, tx1Value, dataFieldTx1, staking.GasLimitForStakeOperation)
tx1Value := big.NewInt(0).Mul(big.NewInt(2499), chainSimulatorIntegrationTests.OneEGLD)
tx1 := chainSimulatorIntegrationTests.GenerateTransaction(wallet1.Bytes, 0, vm.ValidatorSCAddress, tx1Value, dataFieldTx1, staking.GasLimitForStakeOperation)

dataFieldTx2 := fmt.Sprintf("stake@01@%s@%s", blsKeys[1], staking.MockBLSSignature)
tx2 := staking.GenerateTransaction(wallet3.Bytes, 0, vm.ValidatorSCAddress, staking.MinimumStakeValue, dataFieldTx2, staking.GasLimitForStakeOperation)
tx2 := chainSimulatorIntegrationTests.GenerateTransaction(wallet3.Bytes, 0, vm.ValidatorSCAddress, chainSimulatorIntegrationTests.MinimumStakeValue, dataFieldTx2, staking.GasLimitForStakeOperation)

dataFieldTx3 := fmt.Sprintf("stake@01@%s@%s", blsKeys[2], staking.MockBLSSignature)
tx3Value := big.NewInt(0).Mul(big.NewInt(2501), staking.OneEGLD)
tx3 := staking.GenerateTransaction(wallet2.Bytes, 0, vm.ValidatorSCAddress, tx3Value, dataFieldTx3, staking.GasLimitForStakeOperation)
tx3Value := big.NewInt(0).Mul(big.NewInt(2501), chainSimulatorIntegrationTests.OneEGLD)
tx3 := chainSimulatorIntegrationTests.GenerateTransaction(wallet2.Bytes, 0, vm.ValidatorSCAddress, tx3Value, dataFieldTx3, staking.GasLimitForStakeOperation)

results, err := cs.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx1, tx2, tx3}, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
@@ -200,13 +201,13 @@ func TestChainSimulator_StakingV4Step2APICalls(t *testing.T) {
err = cs.AddValidatorKeys(privateKey)
require.Nil(t, err)

mintValue := big.NewInt(0).Add(staking.MinimumStakeValue, staking.OneEGLD)
mintValue := big.NewInt(0).Add(chainSimulatorIntegrationTests.MinimumStakeValue, chainSimulatorIntegrationTests.OneEGLD)
validatorOwner, err := cs.GenerateAndMintWalletAddress(core.AllShardId, mintValue)
require.Nil(t, err)

// Stake a new validator that should end up in auction in step 1
txDataField := fmt.Sprintf("stake@01@%s@%s", blsKeys[0], staking.MockBLSSignature)
txStake := staking.GenerateTransaction(validatorOwner.Bytes, 0, vm.ValidatorSCAddress, staking.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
txStake := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, 0, vm.ValidatorSCAddress, chainSimulatorIntegrationTests.MinimumStakeValue, txDataField, staking.GasLimitForStakeOperation)
stakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, stakeTx)
@@ -226,7 +227,7 @@ func TestChainSimulator_StakingV4Step2APICalls(t *testing.T) {

// re-stake the node
txDataField = fmt.Sprintf("reStakeUnStakedNodes@%s", blsKeys[0])
txReStake := staking.GenerateTransaction(validatorOwner.Bytes, 1, vm.ValidatorSCAddress, big.NewInt(0), txDataField, staking.GasLimitForStakeOperation)
txReStake := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, 1, vm.ValidatorSCAddress, big.NewInt(0), txDataField, staking.GasLimitForStakeOperation)
reStakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txReStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, reStakeTx)
182 changes: 91 additions & 91 deletions integrationTests/chainSimulator/staking/stake/stakeAndUnStake_test.go

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ import (
"time"

"github.com/multiversx/mx-chain-go/config"
chainSimulatorIntegrationTests "github.com/multiversx/mx-chain-go/integrationTests/chainSimulator"
"github.com/multiversx/mx-chain-go/integrationTests/chainSimulator/staking"
"github.com/multiversx/mx-chain-go/node/chainSimulator"
"github.com/multiversx/mx-chain-go/node/chainSimulator/components/api"
@@ -73,7 +74,7 @@ func testStakingProviderWithNodesReStakeUnStaked(t *testing.T, stakingV4Activati
require.NotNil(t, cs)
defer cs.Close()

mintValue := big.NewInt(0).Mul(big.NewInt(5000), staking.OneEGLD)
mintValue := big.NewInt(0).Mul(big.NewInt(5000), chainSimulatorIntegrationTests.OneEGLD)
validatorOwner, err := cs.GenerateAndMintWalletAddress(0, mintValue)
require.Nil(t, err)
require.Nil(t, err)
@@ -84,7 +85,7 @@ func testStakingProviderWithNodesReStakeUnStaked(t *testing.T, stakingV4Activati
// create delegation contract
stakeValue, _ := big.NewInt(0).SetString("4250000000000000000000", 10)
dataField := "createNewDelegationContract@00@0ea1"
txStake := staking.GenerateTransaction(validatorOwner.Bytes, staking.GetNonce(t, cs, validatorOwner), vm.DelegationManagerSCAddress, stakeValue, dataField, 80_000_000)
txStake := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, staking.GetNonce(t, cs, validatorOwner), vm.DelegationManagerSCAddress, stakeValue, dataField, 80_000_000)
stakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txStake, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, stakeTx)
@@ -98,14 +99,14 @@ func testStakingProviderWithNodesReStakeUnStaked(t *testing.T, stakingV4Activati

txDataFieldAddNodes := fmt.Sprintf("addNodes@%s@%s", blsKeys[0], staking.MockBLSSignature+"02")
ownerNonce := staking.GetNonce(t, cs, validatorOwner)
txAddNodes := staking.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), txDataFieldAddNodes, staking.GasLimitForStakeOperation)
txAddNodes := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), txDataFieldAddNodes, staking.GasLimitForStakeOperation)
addNodesTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(txAddNodes, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, addNodesTx)

txDataFieldStakeNodes := fmt.Sprintf("stakeNodes@%s", blsKeys[0])
ownerNonce = staking.GetNonce(t, cs, validatorOwner)
txStakeNodes := staking.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), txDataFieldStakeNodes, staking.GasLimitForStakeOperation)
txStakeNodes := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), txDataFieldStakeNodes, staking.GasLimitForStakeOperation)

stakeNodesTxs, err := cs.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{txStakeNodes}, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
@@ -129,7 +130,7 @@ func testStakingProviderWithNodesReStakeUnStaked(t *testing.T, stakingV4Activati

ownerNonce = staking.GetNonce(t, cs, validatorOwner)
reStakeTxData := fmt.Sprintf("reStakeUnStakedNodes@%s", blsKeys[0])
reStakeNodes := staking.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), reStakeTxData, staking.GasLimitForStakeOperation)
reStakeNodes := chainSimulatorIntegrationTests.GenerateTransaction(validatorOwner.Bytes, ownerNonce, delegationAddressBytes, big.NewInt(0), reStakeTxData, staking.GasLimitForStakeOperation)
reStakeTx, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(reStakeNodes, staking.MaxNumOfBlockToGenerateWhenExecutingTx)
require.Nil(t, err)
require.NotNil(t, reStakeTx)
245 changes: 245 additions & 0 deletions integrationTests/chainSimulator/testing.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
package chainSimulator

import (
"encoding/base64"
"math/big"
"testing"
"time"

"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
"github.com/multiversx/mx-chain-go/node/chainSimulator/errors"
chainSimulatorProcess "github.com/multiversx/mx-chain-go/node/chainSimulator/process"
"github.com/multiversx/mx-chain-go/process"

"github.com/multiversx/mx-chain-core-go/core"
coreAPI "github.com/multiversx/mx-chain-core-go/data/api"
"github.com/multiversx/mx-chain-core-go/data/transaction"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// CheckSetState -
func CheckSetState(t *testing.T, chainSimulator ChainSimulator, nodeHandler chainSimulatorProcess.NodeHandler) {
keyValueMap := map[string]string{
"01": "01",
"02": "02",
}

address := "erd1qtc600lryvytxuy4h7vn7xmsy5tw6vuw3tskr75cwnmv4mnyjgsq6e5zgj"
err := chainSimulator.SetKeyValueForAddress(address, keyValueMap)
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(1)
require.Nil(t, err)

keyValuePairs, _, err := nodeHandler.GetFacadeHandler().GetKeyValuePairs(address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, keyValueMap, keyValuePairs)
}

// CheckSetEntireState -
func CheckSetEntireState(t *testing.T, chainSimulator ChainSimulator, nodeHandler chainSimulatorProcess.NodeHandler, accountState *dtos.AddressState) {
err := chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(30)
require.Nil(t, err)

scAddress, _ := nodeHandler.GetCoreComponents().AddressPubKeyConverter().Decode(accountState.Address)
res, _, err := nodeHandler.GetFacadeHandler().ExecuteSCQuery(&process.SCQuery{
ScAddress: scAddress,
FuncName: "getSum",
CallerAddr: nil,
BlockNonce: core.OptionalUint64{},
})
require.Nil(t, err)

counterValue := big.NewInt(0).SetBytes(res.ReturnData[0]).Int64()
require.Equal(t, 10, int(counterValue))

time.Sleep(time.Second)

account, _, err := nodeHandler.GetFacadeHandler().GetAccount(accountState.Address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))
}

// CheckSetEntireStateWithRemoval -
func CheckSetEntireStateWithRemoval(t *testing.T, chainSimulator ChainSimulator, nodeHandler chainSimulatorProcess.NodeHandler, accountState *dtos.AddressState) {
// activate the auto balancing tries so the results will be the same
err := chainSimulator.GenerateBlocks(30)
require.Nil(t, err)

err = chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

scAddress, _ := nodeHandler.GetCoreComponents().AddressPubKeyConverter().Decode(accountState.Address)
res, _, err := nodeHandler.GetFacadeHandler().ExecuteSCQuery(&process.SCQuery{
ScAddress: scAddress,
FuncName: "getSum",
CallerAddr: nil,
BlockNonce: core.OptionalUint64{},
})
require.Nil(t, err)

counterValue := big.NewInt(0).SetBytes(res.ReturnData[0]).Int64()
require.Equal(t, 10, int(counterValue))

account, _, err := nodeHandler.GetFacadeHandler().GetAccount(accountState.Address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))

// Now we remove the account
err = chainSimulator.RemoveAccounts([]string{accountState.Address})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

account, _, err = nodeHandler.GetFacadeHandler().GetAccount(accountState.Address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, "0", account.Balance)
require.Equal(t, "0", account.DeveloperReward)
require.Equal(t, "", account.Code)
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, "", account.OwnerAddress)
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.RootHash))

// Set the state again
err = chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

account, _, err = nodeHandler.GetFacadeHandler().GetAccount(accountState.Address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)

require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))
}

// CheckGetAccount -
func CheckGetAccount(t *testing.T, chainSimulator ChainSimulator) {
// the facade's GetAccount method requires that at least one block was produced over the genesis block
err := chainSimulator.GenerateBlocks(1)
require.Nil(t, err)

address := dtos.WalletAddress{
Bech32: "erd1qtc600lryvytxuy4h7vn7xmsy5tw6vuw3tskr75cwnmv4mnyjgsq6e5zgj",
}
address.Bytes, err = chainSimulator.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter().Decode(address.Bech32)
require.Nil(t, err)

account, err := chainSimulator.GetAccount(address)
require.Nil(t, err)
require.Equal(t, uint64(0), account.Nonce)
require.Equal(t, "0", account.Balance)

nonce := uint64(37)
err = chainSimulator.SetStateMultiple([]*dtos.AddressState{
{
Address: address.Bech32,
Nonce: &nonce,
Balance: big.NewInt(38).String(),
},
})
require.Nil(t, err)

// without this call the test will fail because the latest produced block points to a state roothash that tells that
// the account has the nonce 0
_ = chainSimulator.GenerateBlocks(1)

account, err = chainSimulator.GetAccount(address)
require.Nil(t, err)
require.Equal(t, uint64(37), account.Nonce)
require.Equal(t, "38", account.Balance)
}

// CheckGenerateTransactions -
func CheckGenerateTransactions(t *testing.T, chainSimulator ChainSimulator) {
transferValue := big.NewInt(0).Mul(OneEGLD, big.NewInt(5))

wallet0, err := chainSimulator.GenerateAndMintWalletAddress(0, InitialAmount)
require.Nil(t, err)

wallet1, err := chainSimulator.GenerateAndMintWalletAddress(1, InitialAmount)
require.Nil(t, err)

wallet2, err := chainSimulator.GenerateAndMintWalletAddress(2, InitialAmount)
require.Nil(t, err)

wallet3, err := chainSimulator.GenerateAndMintWalletAddress(2, InitialAmount)
require.Nil(t, err)

wallet4, err := chainSimulator.GenerateAndMintWalletAddress(2, InitialAmount)
require.Nil(t, err)

gasLimit := uint64(50000)
tx0 := GenerateTransaction(wallet0.Bytes, 0, wallet2.Bytes, transferValue, "", gasLimit)
tx1 := GenerateTransaction(wallet1.Bytes, 0, wallet2.Bytes, transferValue, "", gasLimit)
tx3 := GenerateTransaction(wallet3.Bytes, 0, wallet4.Bytes, transferValue, "", gasLimit)

maxNumOfBlockToGenerateWhenExecutingTx := 15

t.Run("nil or empty slice of transactions should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted(nil, 1)
assert.Equal(t, errors.ErrEmptySliceOfTxs, errSend)
assert.Nil(t, sentTxs)

sentTxs, errSend = chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted(make([]*transaction.Transaction, 0), 1)
assert.Equal(t, errors.ErrEmptySliceOfTxs, errSend)
assert.Nil(t, sentTxs)
})
t.Run("invalid max number of blocks to generate should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx0, tx1}, 0)
assert.Equal(t, errors.ErrInvalidMaxNumOfBlocks, errSend)
assert.Nil(t, sentTxs)
})
t.Run("nil transaction in slice should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{nil}, 1)
assert.ErrorIs(t, errSend, errors.ErrNilTransaction)
assert.Nil(t, sentTxs)
})
t.Run("2 transactions from different shard should call send correctly", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx0, tx1}, maxNumOfBlockToGenerateWhenExecutingTx)
assert.Equal(t, 2, len(sentTxs))
assert.Nil(t, errSend)

account, errGet := chainSimulator.GetAccount(wallet2)
assert.Nil(t, errGet)
expectedBalance := big.NewInt(0).Add(InitialAmount, transferValue)
expectedBalance.Add(expectedBalance, transferValue)
assert.Equal(t, expectedBalance.String(), account.Balance)
})
t.Run("1 transaction should be sent correctly", func(t *testing.T) {
_, errSend := chainSimulator.SendTxAndGenerateBlockTilTxIsExecuted(tx3, maxNumOfBlockToGenerateWhenExecutingTx)
assert.Nil(t, errSend)

account, errGet := chainSimulator.GetAccount(wallet4)
assert.Nil(t, errGet)
expectedBalance := big.NewInt(0).Add(InitialAmount, transferValue)
assert.Equal(t, expectedBalance.String(), account.Balance)
})
}
7 changes: 4 additions & 3 deletions node/chainSimulator/chainSimulator.go
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import (
"github.com/multiversx/mx-chain-go/node/chainSimulator/components"
"github.com/multiversx/mx-chain-go/node/chainSimulator/configs"
"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
chainSimulatorErrors "github.com/multiversx/mx-chain-go/node/chainSimulator/errors"
"github.com/multiversx/mx-chain-go/node/chainSimulator/process"
mxChainSharding "github.com/multiversx/mx-chain-go/sharding"

@@ -516,16 +517,16 @@ func (s *simulator) SendTxAndGenerateBlockTilTxIsExecuted(txToSend *transaction.
// SendTxsAndGenerateBlocksTilAreExecuted will send the provided transactions and generate block until all transactions are executed
func (s *simulator) SendTxsAndGenerateBlocksTilAreExecuted(txsToSend []*transaction.Transaction, maxNumOfBlocksToGenerateWhenExecutingTx int) ([]*transaction.ApiTransactionResult, error) {
if len(txsToSend) == 0 {
return nil, errEmptySliceOfTxs
return nil, chainSimulatorErrors.ErrEmptySliceOfTxs
}
if maxNumOfBlocksToGenerateWhenExecutingTx == 0 {
return nil, errInvalidMaxNumOfBlocks
return nil, chainSimulatorErrors.ErrInvalidMaxNumOfBlocks
}

transactionStatus := make([]*transactionWithResult, 0, len(txsToSend))
for idx, tx := range txsToSend {
if tx == nil {
return nil, fmt.Errorf("%w on position %d", errNilTransaction, idx)
return nil, fmt.Errorf("%w on position %d", chainSimulatorErrors.ErrNilTransaction, idx)
}

txHashHex, err := s.sendTx(tx)
239 changes: 6 additions & 233 deletions node/chainSimulator/chainSimulator_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
package chainSimulator

import (
"encoding/base64"
"math/big"
"testing"
"time"

"github.com/multiversx/mx-chain-go/config"
chainSimulatorCommon "github.com/multiversx/mx-chain-go/integrationTests/chainSimulator"
"github.com/multiversx/mx-chain-go/node/chainSimulator/components/api"
"github.com/multiversx/mx-chain-go/node/chainSimulator/configs"
"github.com/multiversx/mx-chain-go/node/chainSimulator/dtos"
"github.com/multiversx/mx-chain-go/process"

"github.com/multiversx/mx-chain-core-go/core"
coreAPI "github.com/multiversx/mx-chain-core-go/data/api"
"github.com/multiversx/mx-chain-core-go/data/transaction"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -232,22 +228,7 @@ func TestChainSimulator_SetState(t *testing.T) {

defer chainSimulator.Close()

keyValueMap := map[string]string{
"01": "01",
"02": "02",
}

address := "erd1qtc600lryvytxuy4h7vn7xmsy5tw6vuw3tskr75cwnmv4mnyjgsq6e5zgj"
err = chainSimulator.SetKeyValueForAddress(address, keyValueMap)
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(1)
require.Nil(t, err)

nodeHandler := chainSimulator.GetNodeHandler(0)
keyValuePairs, _, err := nodeHandler.GetFacadeHandler().GetKeyValuePairs(address, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, keyValueMap, keyValuePairs)
chainSimulatorCommon.CheckSetState(t, chainSimulator, chainSimulator.GetNodeHandler(0))
}

func TestChainSimulator_SetEntireState(t *testing.T) {
@@ -297,36 +278,7 @@ func TestChainSimulator_SetEntireState(t *testing.T) {
},
}

err = chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(30)
require.Nil(t, err)

nodeHandler := chainSimulator.GetNodeHandler(1)
scAddress, _ := nodeHandler.GetCoreComponents().AddressPubKeyConverter().Decode(contractAddress)
res, _, err := nodeHandler.GetFacadeHandler().ExecuteSCQuery(&process.SCQuery{
ScAddress: scAddress,
FuncName: "getSum",
CallerAddr: nil,
BlockNonce: core.OptionalUint64{},
})
require.Nil(t, err)

counterValue := big.NewInt(0).SetBytes(res.ReturnData[0]).Int64()
require.Equal(t, 10, int(counterValue))

time.Sleep(time.Second)

account, _, err := nodeHandler.GetFacadeHandler().GetAccount(contractAddress, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))
chainSimulatorCommon.CheckSetEntireState(t, chainSimulator, chainSimulator.GetNodeHandler(1), accountState)
}

func TestChainSimulator_SetEntireStateWithRemoval(t *testing.T) {
@@ -359,10 +311,6 @@ func TestChainSimulator_SetEntireStateWithRemoval(t *testing.T) {

defer chainSimulator.Close()

// activate the auto balancing tries so the results will be the same
err = chainSimulator.GenerateBlocks(30)
require.Nil(t, err)

balance := "431271308732096033771131"
contractAddress := "erd1qqqqqqqqqqqqqpgqmzzm05jeav6d5qvna0q2pmcllelkz8xddz3syjszx5"
accountState := &dtos.AddressState{
@@ -379,70 +327,7 @@ func TestChainSimulator_SetEntireStateWithRemoval(t *testing.T) {
"73756d": "0a",
},
}

err = chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

nodeHandler := chainSimulator.GetNodeHandler(1)
scAddress, _ := nodeHandler.GetCoreComponents().AddressPubKeyConverter().Decode(contractAddress)
res, _, err := nodeHandler.GetFacadeHandler().ExecuteSCQuery(&process.SCQuery{
ScAddress: scAddress,
FuncName: "getSum",
CallerAddr: nil,
BlockNonce: core.OptionalUint64{},
})
require.Nil(t, err)

counterValue := big.NewInt(0).SetBytes(res.ReturnData[0]).Int64()
require.Equal(t, 10, int(counterValue))

account, _, err := nodeHandler.GetFacadeHandler().GetAccount(contractAddress, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))

// Now we remove the account
err = chainSimulator.RemoveAccounts([]string{contractAddress})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

account, _, err = nodeHandler.GetFacadeHandler().GetAccount(contractAddress, coreAPI.AccountQueryOptions{})
require.Nil(t, err)
require.Equal(t, "0", account.Balance)
require.Equal(t, "0", account.DeveloperReward)
require.Equal(t, "", account.Code)
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, "", account.OwnerAddress)
require.Equal(t, "", base64.StdEncoding.EncodeToString(account.RootHash))

// Set the state again
err = chainSimulator.SetStateMultiple([]*dtos.AddressState{accountState})
require.Nil(t, err)

err = chainSimulator.GenerateBlocks(2)
require.Nil(t, err)

account, _, err = nodeHandler.GetFacadeHandler().GetAccount(contractAddress, coreAPI.AccountQueryOptions{})
require.Nil(t, err)

require.Equal(t, accountState.Balance, account.Balance)
require.Equal(t, accountState.DeveloperRewards, account.DeveloperReward)
require.Equal(t, accountState.Code, account.Code)
require.Equal(t, accountState.CodeHash, base64.StdEncoding.EncodeToString(account.CodeHash))
require.Equal(t, accountState.CodeMetadata, base64.StdEncoding.EncodeToString(account.CodeMetadata))
require.Equal(t, accountState.Owner, account.OwnerAddress)
require.Equal(t, accountState.RootHash, base64.StdEncoding.EncodeToString(account.RootHash))
chainSimulatorCommon.CheckSetEntireStateWithRemoval(t, chainSimulator, chainSimulator.GetNodeHandler(1), accountState)
}

func TestChainSimulator_GetAccount(t *testing.T) {
@@ -478,35 +363,7 @@ func TestChainSimulator_GetAccount(t *testing.T) {

defer chainSimulator.Close()

address := dtos.WalletAddress{
Bech32: "erd1qtc600lryvytxuy4h7vn7xmsy5tw6vuw3tskr75cwnmv4mnyjgsq6e5zgj",
}
address.Bytes, err = chainSimulator.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter().Decode(address.Bech32)
assert.Nil(t, err)

account, err := chainSimulator.GetAccount(address)
assert.Nil(t, err)
assert.Equal(t, uint64(0), account.Nonce)
assert.Equal(t, "0", account.Balance)

nonce := uint64(37)
err = chainSimulator.SetStateMultiple([]*dtos.AddressState{
{
Address: address.Bech32,
Nonce: &nonce,
Balance: big.NewInt(38).String(),
},
})
assert.Nil(t, err)

// without this call the test will fail because the latest produced block points to a state roothash that tells that
// the account has the nonce 0
_ = chainSimulator.GenerateBlocks(1)

account, err = chainSimulator.GetAccount(address)
assert.Nil(t, err)
assert.Equal(t, uint64(37), account.Nonce)
assert.Equal(t, "38", account.Balance)
chainSimulatorCommon.CheckGetAccount(t, chainSimulator)
}

func TestSimulator_SendTransactions(t *testing.T) {
@@ -539,89 +396,5 @@ func TestSimulator_SendTransactions(t *testing.T) {

defer chainSimulator.Close()

oneEgld := big.NewInt(1000000000000000000)
initialMinting := big.NewInt(0).Mul(oneEgld, big.NewInt(100))
transferValue := big.NewInt(0).Mul(oneEgld, big.NewInt(5))

wallet0, err := chainSimulator.GenerateAndMintWalletAddress(0, initialMinting)
require.Nil(t, err)

wallet1, err := chainSimulator.GenerateAndMintWalletAddress(1, initialMinting)
require.Nil(t, err)

wallet2, err := chainSimulator.GenerateAndMintWalletAddress(2, initialMinting)
require.Nil(t, err)

wallet3, err := chainSimulator.GenerateAndMintWalletAddress(2, initialMinting)
require.Nil(t, err)

wallet4, err := chainSimulator.GenerateAndMintWalletAddress(2, initialMinting)
require.Nil(t, err)

gasLimit := uint64(50000)
tx0 := generateTransaction(wallet0.Bytes, 0, wallet2.Bytes, transferValue, "", gasLimit)
tx1 := generateTransaction(wallet1.Bytes, 0, wallet2.Bytes, transferValue, "", gasLimit)
tx3 := generateTransaction(wallet3.Bytes, 0, wallet4.Bytes, transferValue, "", gasLimit)

maxNumOfBlockToGenerateWhenExecutingTx := 15

t.Run("nil or empty slice of transactions should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted(nil, 1)
assert.Equal(t, errEmptySliceOfTxs, errSend)
assert.Nil(t, sentTxs)

sentTxs, errSend = chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted(make([]*transaction.Transaction, 0), 1)
assert.Equal(t, errEmptySliceOfTxs, errSend)
assert.Nil(t, sentTxs)
})
t.Run("invalid max number of blocks to generate should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx0, tx1}, 0)
assert.Equal(t, errInvalidMaxNumOfBlocks, errSend)
assert.Nil(t, sentTxs)
})
t.Run("nil transaction in slice should error", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{nil}, 1)
assert.ErrorIs(t, errSend, errNilTransaction)
assert.Nil(t, sentTxs)
})
t.Run("2 transactions from different shard should call send correctly", func(t *testing.T) {
sentTxs, errSend := chainSimulator.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx0, tx1}, maxNumOfBlockToGenerateWhenExecutingTx)
assert.Equal(t, 2, len(sentTxs))
assert.Nil(t, errSend)

account, errGet := chainSimulator.GetAccount(wallet2)
assert.Nil(t, errGet)
expectedBalance := big.NewInt(0).Add(initialMinting, transferValue)
expectedBalance.Add(expectedBalance, transferValue)
assert.Equal(t, expectedBalance.String(), account.Balance)
})
t.Run("1 transaction should be sent correctly", func(t *testing.T) {
_, errSend := chainSimulator.SendTxAndGenerateBlockTilTxIsExecuted(tx3, maxNumOfBlockToGenerateWhenExecutingTx)
assert.Nil(t, errSend)

account, errGet := chainSimulator.GetAccount(wallet4)
assert.Nil(t, errGet)
expectedBalance := big.NewInt(0).Add(initialMinting, transferValue)
assert.Equal(t, expectedBalance.String(), account.Balance)
})
}

func generateTransaction(sender []byte, nonce uint64, receiver []byte, value *big.Int, data string, gasLimit uint64) *transaction.Transaction {
minGasPrice := uint64(1000000000)
txVersion := uint32(1)
mockTxSignature := "sig"

transferValue := big.NewInt(0).Set(value)
return &transaction.Transaction{
Nonce: nonce,
Value: transferValue,
SndAddr: sender,
RcvAddr: receiver,
Data: []byte(data),
GasLimit: gasLimit,
GasPrice: minGasPrice,
ChainID: []byte(configs.ChainID),
Version: txVersion,
Signature: []byte(mockTxSignature),
}
chainSimulatorCommon.CheckGenerateTransactions(t, chainSimulator)
}
9 changes: 3 additions & 6 deletions node/chainSimulator/errors.go
Original file line number Diff line number Diff line change
@@ -3,10 +3,7 @@ package chainSimulator
import "errors"

var (
errNilChainSimulator = errors.New("nil chain simulator")
errNilMetachainNode = errors.New("nil metachain node")
errShardSetupError = errors.New("shard setup error")
errEmptySliceOfTxs = errors.New("empty slice of transactions to send")
errNilTransaction = errors.New("nil transaction")
errInvalidMaxNumOfBlocks = errors.New("invalid max number of blocks to generate")
errNilChainSimulator = errors.New("nil chain simulator")
errNilMetachainNode = errors.New("nil metachain node")
errShardSetupError = errors.New("shard setup error")
)
12 changes: 12 additions & 0 deletions node/chainSimulator/errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package errors

import "errors"

// ErrEmptySliceOfTxs signals that an empty slice of transactions has been provided
var ErrEmptySliceOfTxs = errors.New("empty slice of transactions to send")

// ErrNilTransaction signals that a nil transaction has been provided
var ErrNilTransaction = errors.New("nil transaction")

// ErrInvalidMaxNumOfBlocks signals that an invalid max numerof blocks has been provided
var ErrInvalidMaxNumOfBlocks = errors.New("invalid max number of blocks to generate")

0 comments on commit 19b1685

Please sign in to comment.