From 7005551274cc1b9d461e7ff86cd0fa5b374a2c60 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Fri, 18 Oct 2024 19:00:04 +0300 Subject: [PATCH 01/13] reverted relayed v3 --- api/groups/transactionGroup.go | 128 +--- api/groups/transactionGroup_test.go | 62 -- cmd/node/config/enableEpochs.toml | 7 +- common/constants.go | 4 - common/enablers/enableEpochsHandler.go | 6 - common/enablers/enableEpochsHandler_test.go | 11 +- config/epochConfig.go | 1 - config/tomlConfig_test.go | 16 +- .../epochStartInterceptorsContainerFactory.go | 2 - errors/errors.go | 3 - factory/interface.go | 1 - factory/mock/processComponentsStub.go | 6 - factory/processing/blockProcessorCreator.go | 146 ++--- .../processing/blockProcessorCreator_test.go | 2 - factory/processing/export_test.go | 6 +- factory/processing/processComponents.go | 24 +- .../processing/processComponentsHandler.go | 15 - .../processComponentsHandler_test.go | 2 - .../txSimulatorProcessComponents.go | 142 ++-- .../txSimulatorProcessComponents_test.go | 7 +- genesis/process/disabled/feeHandler.go | 5 - genesis/process/metaGenesisBlockCreator.go | 51 +- genesis/process/shardGenesisBlockCreator.go | 91 ++- go.mod | 4 +- go.sum | 8 +- .../relayedTx/relayedTx_test.go | 587 +---------------- .../mock/processComponentsStub.go | 6 - .../multiShard/relayedTx/common.go | 81 +-- .../multiShard/relayedTx/relayedTx_test.go | 4 - integrationTests/testHeartbeatNode.go | 2 - integrationTests/testInitializer.go | 21 +- integrationTests/testProcessorNode.go | 180 +++-- .../testProcessorNodeWithTestWebServer.go | 1 - integrationTests/vm/testInitializer.go | 225 +++---- integrationTests/vm/wasm/utils.go | 54 +- .../vm/wasm/wasmvm/wasmVM_test.go | 37 +- .../components/processComponents.go | 7 - .../components/processComponents_test.go | 1 - node/external/dtos.go | 35 +- .../transactionAPI/gasUsedAndFeeProcessor.go | 31 +- .../gasUsedAndFeeProcessor_test.go | 67 +- .../testData/relayedV3WithOneRefund.json | 56 -- node/external/transactionAPI/unmarshaller.go | 131 +--- node/metrics/metrics.go | 1 - node/metrics/metrics_test.go | 14 +- node/node.go | 36 +- node/node_test.go | 33 +- .../transactionsFeeProcessor.go | 47 +- process/block/preprocess/gasComputation.go | 2 +- process/constants.go | 4 - process/coordinator/transactionType.go | 9 - process/coordinator/transactionType_test.go | 26 - process/disabled/failedTxLogsAccumulator.go | 33 - process/disabled/relayedTxV3Processor.go | 23 - process/economics/economicsData.go | 98 --- process/economics/economicsData_test.go | 133 ---- process/errors.go | 45 -- process/factory/interceptorscontainer/args.go | 1 - .../metaInterceptorsContainerFactory.go | 1 - .../metaInterceptorsContainerFactory_test.go | 2 - .../shardInterceptorsContainerFactory.go | 1 - .../shardInterceptorsContainerFactory_test.go | 2 - .../factory/argInterceptedDataFactory.go | 1 - .../interceptedMetaHeaderDataFactory_test.go | 2 - .../factory/interceptedTxDataFactory.go | 4 - process/interface.go | 16 - .../processProxy/processProxy.go | 47 +- .../processProxy/processProxy_test.go | 8 +- .../processProxy/testProcessProxy.go | 47 +- process/smartContract/process_test.go | 12 +- .../smartContract/processorV2/processV2.go | 86 ++- .../smartContract/processorV2/process_test.go | 31 +- process/smartContract/scrCommon/common.go | 47 +- process/transaction/export_test.go | 6 +- process/transaction/interceptedTransaction.go | 83 +-- .../interceptedTransaction_test.go | 368 +---------- process/transaction/relayedTxV3Processor.go | 112 ---- .../transaction/relayedTxV3Processor_test.go | 249 ------- process/transaction/shardProcess.go | 327 ++-------- process/transaction/shardProcess_test.go | 613 +----------------- .../transactionEvaluator.go | 2 +- .../transactionLog/failedTxLogsAccumulator.go | 109 ---- .../failedTxLogsAccumulator_test.go | 168 ----- sharding/mock/enableEpochsHandlerMock.go | 15 - testscommon/components/default.go | 4 +- .../economicsDataHandlerStub.go | 19 - .../economicsmocks/economicsHandlerMock.go | 19 - .../failedTxLogsAccumulatorMock.go | 41 -- .../processMocks/relayedTxV3ProcessorMock.go | 23 - update/factory/exportHandlerFactory.go | 2 - update/factory/fullSyncInterceptors.go | 2 - 91 files changed, 808 insertions(+), 4442 deletions(-) delete mode 100644 node/external/transactionAPI/testData/relayedV3WithOneRefund.json delete mode 100644 process/disabled/failedTxLogsAccumulator.go delete mode 100644 process/disabled/relayedTxV3Processor.go delete mode 100644 process/transaction/relayedTxV3Processor.go delete mode 100644 process/transaction/relayedTxV3Processor_test.go delete mode 100644 process/transactionLog/failedTxLogsAccumulator.go delete mode 100644 process/transactionLog/failedTxLogsAccumulator_test.go delete mode 100644 testscommon/processMocks/failedTxLogsAccumulatorMock.go delete mode 100644 testscommon/processMocks/relayedTxV3ProcessorMock.go diff --git a/api/groups/transactionGroup.go b/api/groups/transactionGroup.go index 83eb97136b8..f35969ed701 100644 --- a/api/groups/transactionGroup.go +++ b/api/groups/transactionGroup.go @@ -197,23 +197,7 @@ func (tg *transactionGroup) simulateTransaction(c *gin.Context) { return } - innerTxs, err := tg.extractInnerTransactions(ftx.InnerTransactions) - if err != nil { - c.JSON( - http.StatusBadRequest, - shared.GenericAPIResponse{ - Data: nil, - Error: fmt.Sprintf("%s: %s", errors.ErrTxGenerationFailed.Error(), err.Error()), - Code: shared.ReturnCodeRequestError, - }, - ) - return - } - - if len(innerTxs) == 0 { - innerTxs = nil - } - tx, txHash, err := tg.createTransaction(&ftx, innerTxs) + tx, txHash, err := tg.createTransaction(&ftx) if err != nil { c.JSON( http.StatusBadRequest, @@ -283,23 +267,7 @@ func (tg *transactionGroup) sendTransaction(c *gin.Context) { return } - innerTxs, err := tg.extractInnerTransactions(ftx.InnerTransactions) - if err != nil { - c.JSON( - http.StatusBadRequest, - shared.GenericAPIResponse{ - Data: nil, - Error: fmt.Sprintf("%s: %s", errors.ErrTxGenerationFailed.Error(), err.Error()), - Code: shared.ReturnCodeRequestError, - }, - ) - return - } - - if len(innerTxs) == 0 { - innerTxs = nil - } - tx, txHash, err := tg.createTransaction(&ftx, innerTxs) + tx, txHash, err := tg.createTransaction(&ftx) if err != nil { c.JSON( http.StatusBadRequest, @@ -378,23 +346,7 @@ func (tg *transactionGroup) sendMultipleTransactions(c *gin.Context) { var start time.Time txsHashes := make(map[int]string) for idx, receivedTx := range ftxs { - innerTxs, errExtractInnerTransactions := tg.extractInnerTransactions(receivedTx.InnerTransactions) - if errExtractInnerTransactions != nil { - c.JSON( - http.StatusBadRequest, - shared.GenericAPIResponse{ - Data: nil, - Error: fmt.Sprintf("%s: %s", errors.ErrTxGenerationFailed.Error(), err.Error()), - Code: shared.ReturnCodeInternalError, - }, - ) - return - } - - if len(innerTxs) == 0 { - innerTxs = nil - } - tx, txHash, err = tg.createTransaction(&receivedTx, innerTxs) + tx, txHash, err = tg.createTransaction(&receivedTx) if err != nil { continue } @@ -556,23 +508,7 @@ func (tg *transactionGroup) computeTransactionGasLimit(c *gin.Context) { return } - innerTxs, errExtractInnerTransactions := tg.extractInnerTransactions(ftx.InnerTransactions) - if errExtractInnerTransactions != nil { - c.JSON( - http.StatusBadRequest, - shared.GenericAPIResponse{ - Data: nil, - Error: fmt.Sprintf("%s: %s", errors.ErrTxGenerationFailed.Error(), errExtractInnerTransactions.Error()), - Code: shared.ReturnCodeInternalError, - }, - ) - return - } - - if len(innerTxs) == 0 { - innerTxs = nil - } - tx, _, err := tg.createTransaction(&ftx, innerTxs) + tx, _, err := tg.createTransaction(&ftx) if err != nil { c.JSON( http.StatusInternalServerError, @@ -782,25 +718,23 @@ func (tg *transactionGroup) getTransactionsPoolNonceGapsForSender(sender string, ) } -func (tg *transactionGroup) createTransaction(receivedTx *transaction.FrontendTransaction, innerTxs []*transaction.Transaction) (*transaction.Transaction, []byte, error) { +func (tg *transactionGroup) createTransaction(receivedTx *transaction.FrontendTransaction) (*transaction.Transaction, []byte, error) { txArgs := &external.ArgsCreateTransaction{ - Nonce: receivedTx.Nonce, - Value: receivedTx.Value, - Receiver: receivedTx.Receiver, - ReceiverUsername: receivedTx.ReceiverUsername, - Sender: receivedTx.Sender, - SenderUsername: receivedTx.SenderUsername, - GasPrice: receivedTx.GasPrice, - GasLimit: receivedTx.GasLimit, - DataField: receivedTx.Data, - SignatureHex: receivedTx.Signature, - ChainID: receivedTx.ChainID, - Version: receivedTx.Version, - Options: receivedTx.Options, - Guardian: receivedTx.GuardianAddr, - GuardianSigHex: receivedTx.GuardianSignature, - Relayer: receivedTx.Relayer, - InnerTransactions: innerTxs, + Nonce: receivedTx.Nonce, + Value: receivedTx.Value, + Receiver: receivedTx.Receiver, + ReceiverUsername: receivedTx.ReceiverUsername, + Sender: receivedTx.Sender, + SenderUsername: receivedTx.SenderUsername, + GasPrice: receivedTx.GasPrice, + GasLimit: receivedTx.GasLimit, + DataField: receivedTx.Data, + SignatureHex: receivedTx.Signature, + ChainID: receivedTx.ChainID, + Version: receivedTx.Version, + Options: receivedTx.Options, + Guardian: receivedTx.GuardianAddr, + GuardianSigHex: receivedTx.GuardianSignature, } start := time.Now() tx, txHash, err := tg.getFacade().CreateTransaction(txArgs) @@ -906,28 +840,6 @@ func (tg *transactionGroup) getFacade() transactionFacadeHandler { return tg.facade } -func (tg *transactionGroup) extractInnerTransactions( - innerTransactions []*transaction.FrontendTransaction, -) ([]*transaction.Transaction, error) { - innerTxs := make([]*transaction.Transaction, 0, len(innerTransactions)) - if len(innerTransactions) != 0 { - for _, innerTx := range innerTransactions { - if len(innerTx.InnerTransactions) != 0 { - return innerTxs, errors.ErrRecursiveRelayedTxIsNotAllowed - } - - newInnerTx, _, err := tg.createTransaction(innerTx, nil) - if err != nil { - return innerTxs, err - } - - innerTxs = append(innerTxs, newInnerTx) - } - } - - return innerTxs, nil -} - // UpdateFacade will update the facade func (tg *transactionGroup) UpdateFacade(newFacade interface{}) error { if newFacade == nil { diff --git a/api/groups/transactionGroup_test.go b/api/groups/transactionGroup_test.go index e517f51f8bd..9f603412ae0 100644 --- a/api/groups/transactionGroup_test.go +++ b/api/groups/transactionGroup_test.go @@ -312,7 +312,6 @@ func TestTransactionGroup_sendTransaction(t *testing.T) { expectedErr, ) }) - t.Run("recursive relayed v3 should error", testRecursiveRelayedV3("/transaction/send")) t.Run("should work", func(t *testing.T) { t.Parallel() @@ -591,7 +590,6 @@ func TestTransactionGroup_computeTransactionGasLimit(t *testing.T) { expectedErr, ) }) - t.Run("recursive relayed v3 should error", testRecursiveRelayedV3("/transaction/cost")) t.Run("should work", func(t *testing.T) { t.Parallel() @@ -712,7 +710,6 @@ func TestTransactionGroup_simulateTransaction(t *testing.T) { expectedErr, ) }) - t.Run("recursive relayed v3 should error", testRecursiveRelayedV3("/transaction/simulate")) t.Run("should work", func(t *testing.T) { t.Parallel() @@ -1201,62 +1198,3 @@ func getTransactionRoutesConfig() config.ApiRoutesConfig { }, } } - -func testRecursiveRelayedV3(url string) func(t *testing.T) { - return func(t *testing.T) { - t.Parallel() - - facade := &mock.FacadeStub{ - CreateTransactionHandler: func(txArgs *external.ArgsCreateTransaction) (*dataTx.Transaction, []byte, error) { - txHash, _ := hex.DecodeString(hexTxHash) - return nil, txHash, nil - }, - SendBulkTransactionsHandler: func(txs []*dataTx.Transaction) (u uint64, err error) { - return 1, nil - }, - ValidateTransactionHandler: func(tx *dataTx.Transaction) error { - return nil - }, - } - - userTx1 := fmt.Sprintf(`{"nonce": %d, "sender":"%s", "receiver":"%s", "value":"%s", "signature":"%s"}`, - nonce, - sender, - receiver, - value, - signature, - ) - userTx2 := fmt.Sprintf(`{"nonce": %d, "sender":"%s", "receiver":"%s", "value":"%s", "signature":"%s", "innerTransactions":[%s]}`, - nonce, - sender, - receiver, - value, - signature, - userTx1, - ) - tx := fmt.Sprintf(`{"nonce": %d, "sender":"%s", "receiver":"%s", "value":"%s", "signature":"%s", "innerTransactions":[%s]}`, - nonce, - sender, - receiver, - value, - signature, - userTx2, - ) - - transactionGroup, err := groups.NewTransactionGroup(facade) - require.NoError(t, err) - - ws := startWebServer(transactionGroup, "transaction", getTransactionRoutesConfig()) - - req, _ := http.NewRequest("POST", url, bytes.NewBuffer([]byte(tx))) - resp := httptest.NewRecorder() - ws.ServeHTTP(resp, req) - - txResp := shared.GenericAPIResponse{} - loadResponse(resp.Body, &txResp) - - assert.Equal(t, http.StatusBadRequest, resp.Code) - assert.True(t, strings.Contains(txResp.Error, apiErrors.ErrRecursiveRelayedTxIsNotAllowed.Error())) - assert.Empty(t, txResp.Data) - } -} diff --git a/cmd/node/config/enableEpochs.toml b/cmd/node/config/enableEpochs.toml index 7f41c21468a..9ca2083a352 100644 --- a/cmd/node/config/enableEpochs.toml +++ b/cmd/node/config/enableEpochs.toml @@ -324,17 +324,14 @@ # UnjailCleanupEnableEpoch represents the epoch when the cleanup of the unjailed nodes is enabled UnJailCleanupEnableEpoch = 4 - # RelayedTransactionsV3EnableEpoch represents the epoch when the relayed transactions V3 will be enabled - RelayedTransactionsV3EnableEpoch = 7 - # FixRelayedBaseCostEnableEpoch represents the epoch when the fix for relayed base cost will be enabled - FixRelayedBaseCostEnableEpoch = 7 + FixRelayedBaseCostEnableEpoch = 4 # MultiESDTNFTTransferAndExecuteByUserEnableEpoch represents the epoch when enshrined sovereign cross chain opcodes are enabled MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 9999999 # FixRelayedMoveBalanceToNonPayableSCEnableEpoch represents the epoch when the fix for relayed move balance to non payable sc will be enabled - FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 7 + FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 4 # BLSMultiSignerEnableEpoch represents the activation epoch for different types of BLS multi-signers BLSMultiSignerEnableEpoch = [ diff --git a/common/constants.go b/common/constants.go index cbcd0caa6c8..2b56d2f388b 100644 --- a/common/constants.go +++ b/common/constants.go @@ -495,9 +495,6 @@ const ( // MetricRelayedTransactionsV2EnableEpoch represents the epoch when the relayed transactions v2 is enabled MetricRelayedTransactionsV2EnableEpoch = "erd_relayed_transactions_v2_enable_epoch" - // MetricRelayedTransactionsV3EnableEpoch represents the epoch when the relayed transactions v3 is enabled - MetricRelayedTransactionsV3EnableEpoch = "erd_relayed_transactions_v3_enable_epoch" - // MetricFixRelayedBaseCostEnableEpoch represents the epoch when the fix for relayed base cost is enabled MetricFixRelayedBaseCostEnableEpoch = "erd_fix_relayed_base_cost_enable_epoch" @@ -1234,7 +1231,6 @@ const ( EGLDInESDTMultiTransferFlag core.EnableEpochFlag = "EGLDInESDTMultiTransferFlag" CryptoOpcodesV2Flag core.EnableEpochFlag = "CryptoOpcodesV2Flag" UnJailCleanupFlag core.EnableEpochFlag = "UnJailCleanupFlag" - RelayedTransactionsV3Flag core.EnableEpochFlag = "RelayedTransactionsV3Flag" FixRelayedBaseCostFlag core.EnableEpochFlag = "FixRelayedBaseCostFlag" MultiESDTNFTTransferAndExecuteByUserFlag core.EnableEpochFlag = "MultiESDTNFTTransferAndExecuteByUserFlag" FixRelayedMoveBalanceToNonPayableSCFlag core.EnableEpochFlag = "FixRelayedMoveBalanceToNonPayableSCFlag" diff --git a/common/enablers/enableEpochsHandler.go b/common/enablers/enableEpochsHandler.go index cba4bb4fb4a..65cc7762796 100644 --- a/common/enablers/enableEpochsHandler.go +++ b/common/enablers/enableEpochsHandler.go @@ -762,12 +762,6 @@ func (handler *enableEpochsHandler) createAllFlagsMap() { }, activationEpoch: handler.enableEpochsConfig.UnJailCleanupEnableEpoch, }, - common.RelayedTransactionsV3Flag: { - isActiveInEpoch: func(epoch uint32) bool { - return epoch >= handler.enableEpochsConfig.RelayedTransactionsV3EnableEpoch - }, - activationEpoch: handler.enableEpochsConfig.RelayedTransactionsV3EnableEpoch, - }, common.FixRelayedBaseCostFlag: { isActiveInEpoch: func(epoch uint32) bool { return epoch >= handler.enableEpochsConfig.FixRelayedBaseCostEnableEpoch diff --git a/common/enablers/enableEpochsHandler_test.go b/common/enablers/enableEpochsHandler_test.go index b7d8f27692d..d0f9191055e 100644 --- a/common/enablers/enableEpochsHandler_test.go +++ b/common/enablers/enableEpochsHandler_test.go @@ -119,11 +119,10 @@ func createEnableEpochsConfig() config.EnableEpochs { DynamicESDTEnableEpoch: 102, EGLDInMultiTransferEnableEpoch: 103, CryptoOpcodesV2EnableEpoch: 104, - RelayedTransactionsV3EnableEpoch: 105, - FixRelayedBaseCostEnableEpoch: 106, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 107, - FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 108, - UseGasBoundedShouldFailExecutionEnableEpoch: 110, + FixRelayedBaseCostEnableEpoch: 105, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 106, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 107, + UseGasBoundedShouldFailExecutionEnableEpoch: 108, } } @@ -324,7 +323,6 @@ func TestEnableEpochsHandler_IsFlagEnabled(t *testing.T) { require.True(t, handler.IsFlagEnabled(common.StakingV4StartedFlag)) require.True(t, handler.IsFlagEnabled(common.AlwaysMergeContextsInEEIFlag)) require.True(t, handler.IsFlagEnabled(common.DynamicESDTFlag)) - require.True(t, handler.IsFlagEnabled(common.RelayedTransactionsV3Flag)) require.True(t, handler.IsFlagEnabled(common.FixRelayedBaseCostFlag)) require.True(t, handler.IsFlagEnabled(common.FixRelayedMoveBalanceToNonPayableSCFlag)) } @@ -447,7 +445,6 @@ func TestEnableEpochsHandler_GetActivationEpoch(t *testing.T) { require.Equal(t, cfg.DynamicESDTEnableEpoch, handler.GetActivationEpoch(common.DynamicESDTFlag)) require.Equal(t, cfg.EGLDInMultiTransferEnableEpoch, handler.GetActivationEpoch(common.EGLDInESDTMultiTransferFlag)) require.Equal(t, cfg.CryptoOpcodesV2EnableEpoch, handler.GetActivationEpoch(common.CryptoOpcodesV2Flag)) - require.Equal(t, cfg.RelayedTransactionsV3EnableEpoch, handler.GetActivationEpoch(common.RelayedTransactionsV3Flag)) require.Equal(t, cfg.FixRelayedBaseCostEnableEpoch, handler.GetActivationEpoch(common.FixRelayedBaseCostFlag)) require.Equal(t, cfg.MultiESDTNFTTransferAndExecuteByUserEnableEpoch, handler.GetActivationEpoch(common.MultiESDTNFTTransferAndExecuteByUserFlag)) require.Equal(t, cfg.FixRelayedMoveBalanceToNonPayableSCEnableEpoch, handler.GetActivationEpoch(common.FixRelayedMoveBalanceToNonPayableSCFlag)) diff --git a/config/epochConfig.go b/config/epochConfig.go index e24c302b7d0..a7fd67c680a 100644 --- a/config/epochConfig.go +++ b/config/epochConfig.go @@ -119,7 +119,6 @@ type EnableEpochs struct { EGLDInMultiTransferEnableEpoch uint32 CryptoOpcodesV2EnableEpoch uint32 UnJailCleanupEnableEpoch uint32 - RelayedTransactionsV3EnableEpoch uint32 FixRelayedBaseCostEnableEpoch uint32 MultiESDTNFTTransferAndExecuteByUserEnableEpoch uint32 FixRelayedMoveBalanceToNonPayableSCEnableEpoch uint32 diff --git a/config/tomlConfig_test.go b/config/tomlConfig_test.go index f331917c5d0..e7095b0b096 100644 --- a/config/tomlConfig_test.go +++ b/config/tomlConfig_test.go @@ -875,17 +875,14 @@ func TestEnableEpochConfig(t *testing.T) { # CryptoOpcodesV2EnableEpoch represents the epoch when BLSMultiSig, Secp256r1 and other opcodes are enabled CryptoOpcodesV2EnableEpoch = 98 - # RelayedTransactionsV3EnableEpoch represents the epoch when the relayed transactions V3 will be enabled - RelayedTransactionsV3EnableEpoch = 99 - # FixRelayedBaseCostEnableEpoch represents the epoch when the fix for relayed base cost will be enabled - FixRelayedBaseCostEnableEpoch = 100 + FixRelayedBaseCostEnableEpoch = 99 # MultiESDTNFTTransferAndExecuteByUserEnableEpoch represents the epoch when enshrined sovereign cross chain opcodes are enabled - MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 101 + MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 100 # FixRelayedMoveBalanceToNonPayableSCEnableEpoch represents the epoch when the fix for relayed move balance to non payable sc will be enabled - FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 102 + FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 101 # MaxNodesChangeEnableEpoch holds configuration for changing the maximum number of nodes and the enabling epoch MaxNodesChangeEnableEpoch = [ @@ -1004,10 +1001,9 @@ func TestEnableEpochConfig(t *testing.T) { DynamicESDTEnableEpoch: 96, EGLDInMultiTransferEnableEpoch: 97, CryptoOpcodesV2EnableEpoch: 98, - RelayedTransactionsV3EnableEpoch: 99, - FixRelayedBaseCostEnableEpoch: 100, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 101, - FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 102, + FixRelayedBaseCostEnableEpoch: 99, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 100, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 101, MaxNodesChangeEnableEpoch: []MaxNodesChangeConfig{ { EpochEnable: 44, diff --git a/epochStart/bootstrap/factory/epochStartInterceptorsContainerFactory.go b/epochStart/bootstrap/factory/epochStartInterceptorsContainerFactory.go index 0ebf8417d7b..d659989896b 100644 --- a/epochStart/bootstrap/factory/epochStartInterceptorsContainerFactory.go +++ b/epochStart/bootstrap/factory/epochStartInterceptorsContainerFactory.go @@ -14,7 +14,6 @@ import ( disabledFactory "github.com/multiversx/mx-chain-go/factory/disabled" disabledGenesis "github.com/multiversx/mx-chain-go/genesis/process/disabled" "github.com/multiversx/mx-chain-go/process" - processDisabled "github.com/multiversx/mx-chain-go/process/disabled" "github.com/multiversx/mx-chain-go/process/factory/interceptorscontainer" "github.com/multiversx/mx-chain-go/sharding" "github.com/multiversx/mx-chain-go/storage/cache" @@ -109,7 +108,6 @@ func NewEpochStartInterceptorsContainer(args ArgsEpochStartInterceptorContainer) FullArchivePeerShardMapper: fullArchivePeerShardMapper, HardforkTrigger: hardforkTrigger, NodeOperationMode: args.NodeOperationMode, - RelayedTxV3Processor: processDisabled.NewRelayedTxV3Processor(), } interceptorsContainerFactory, err := interceptorscontainer.NewMetaInterceptorsContainerFactory(containerFactoryArgs) diff --git a/errors/errors.go b/errors/errors.go index b1edc990afc..dd475327876 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -598,6 +598,3 @@ var ErrNilSentSignatureTracker = errors.New("nil sent signature tracker") // ErrNilEpochSystemSCProcessor defines the error for setting a nil EpochSystemSCProcessor var ErrNilEpochSystemSCProcessor = errors.New("nil epoch system SC processor") - -// ErrNilRelayedTxV3Processor signals that a nil relayed tx v3 processor has been provided -var ErrNilRelayedTxV3Processor = errors.New("nil relayed tx v3 processor") diff --git a/factory/interface.go b/factory/interface.go index ec92f478992..0f1c237d0d9 100644 --- a/factory/interface.go +++ b/factory/interface.go @@ -311,7 +311,6 @@ type ProcessComponentsHolder interface { ReceiptsRepository() ReceiptsRepository SentSignaturesTracker() process.SentSignaturesTracker EpochSystemSCProcessor() process.EpochStartSystemSCProcessor - RelayedTxV3Processor() process.RelayedTxV3Processor IsInterfaceNil() bool } diff --git a/factory/mock/processComponentsStub.go b/factory/mock/processComponentsStub.go index 4a52413b7cd..32bbfaf2df3 100644 --- a/factory/mock/processComponentsStub.go +++ b/factory/mock/processComponentsStub.go @@ -58,7 +58,6 @@ type ProcessComponentsMock struct { ReceiptsRepositoryInternal factory.ReceiptsRepository SentSignaturesTrackerInternal process.SentSignaturesTracker EpochSystemSCProcessorInternal process.EpochStartSystemSCProcessor - RelayedTxV3ProcessorField process.RelayedTxV3Processor } // Create - @@ -291,11 +290,6 @@ func (pcm *ProcessComponentsMock) EpochSystemSCProcessor() process.EpochStartSys return pcm.EpochSystemSCProcessorInternal } -// RelayedTxV3Processor - -func (pcm *ProcessComponentsMock) RelayedTxV3Processor() process.RelayedTxV3Processor { - return pcm.RelayedTxV3ProcessorField -} - // IsInterfaceNil - func (pcm *ProcessComponentsMock) IsInterfaceNil() bool { return pcm == nil diff --git a/factory/processing/blockProcessorCreator.go b/factory/processing/blockProcessorCreator.go index c48a777f01c..0721efc6a23 100644 --- a/factory/processing/blockProcessorCreator.go +++ b/factory/processing/blockProcessorCreator.go @@ -38,7 +38,6 @@ import ( "github.com/multiversx/mx-chain-go/process/smartContract/scrCommon" "github.com/multiversx/mx-chain-go/process/throttle" "github.com/multiversx/mx-chain-go/process/transaction" - "github.com/multiversx/mx-chain-go/process/transactionLog" "github.com/multiversx/mx-chain-go/state" "github.com/multiversx/mx-chain-go/state/syncer" "github.com/multiversx/mx-chain-go/storage/txcache" @@ -70,7 +69,6 @@ func (pcf *processComponentsFactory) newBlockProcessor( blockCutoffProcessingHandler cutoff.BlockProcessingCutoffHandler, missingTrieNodesNotifier common.MissingTrieNodesNotifier, sentSignaturesTracker process.SentSignaturesTracker, - relayedTxV3Processor process.RelayedTxV3Processor, ) (*blockProcessorAndVmFactories, error) { shardCoordinator := pcf.bootstrapComponents.ShardCoordinator() if shardCoordinator.SelfId() < shardCoordinator.NumberOfShards() { @@ -89,7 +87,6 @@ func (pcf *processComponentsFactory) newBlockProcessor( blockCutoffProcessingHandler, missingTrieNodesNotifier, sentSignaturesTracker, - relayedTxV3Processor, ) } if shardCoordinator.SelfId() == core.MetachainShardId { @@ -131,7 +128,6 @@ func (pcf *processComponentsFactory) newShardBlockProcessor( blockProcessingCutoffHandler cutoff.BlockProcessingCutoffHandler, missingTrieNodesNotifier common.MissingTrieNodesNotifier, sentSignaturesTracker process.SentSignaturesTracker, - relayedTxV3Processor process.RelayedTxV3Processor, ) (*blockProcessorAndVmFactories, error) { argsParser := smartContract.NewArgumentParser() @@ -233,11 +229,6 @@ func (pcf *processComponentsFactory) newShardBlockProcessor( return nil, err } - err = pcf.coreData.EconomicsData().SetTxTypeHandler(txTypeHandler) - if err != nil { - return nil, err - } - gasHandler, err := preprocess.NewGasComputation( pcf.coreData.EconomicsData(), txTypeHandler, @@ -247,32 +238,30 @@ func (pcf *processComponentsFactory) newShardBlockProcessor( return nil, err } - failedTxLogsAccumulator := transactionLog.NewFailedTxLogsAccumulator() txFeeHandler := postprocess.NewFeeAccumulator() argsNewScProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: argsParser, - Hasher: pcf.coreData.Hasher(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - AccountsDB: pcf.state.AccountsAdapter(), - BlockChainHook: vmFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScrForwarder: scForwarder, - TxFeeHandler: txFeeHandler, - EconomicsFee: pcf.coreData.EconomicsData(), - GasHandler: gasHandler, - GasSchedule: pcf.gasSchedule, - TxLogsProcessor: pcf.txLogsProcessor, - TxTypeHandler: txTypeHandler, - IsGenesisProcessing: false, - BadTxForwarder: badTxInterim, - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: wasmVMChangeLocker, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + VmContainer: vmContainer, + ArgsParser: argsParser, + Hasher: pcf.coreData.Hasher(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + AccountsDB: pcf.state.AccountsAdapter(), + BlockChainHook: vmFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScrForwarder: scForwarder, + TxFeeHandler: txFeeHandler, + EconomicsFee: pcf.coreData.EconomicsData(), + GasHandler: gasHandler, + GasSchedule: pcf.gasSchedule, + TxLogsProcessor: pcf.txLogsProcessor, + TxTypeHandler: txTypeHandler, + IsGenesisProcessing: false, + BadTxForwarder: badTxInterim, + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: wasmVMChangeLocker, } scProcessorProxy, err := processProxy.NewSmartContractProcessorProxy(argsNewScProcessor, pcf.epochNotifier) @@ -290,27 +279,25 @@ func (pcf *processComponentsFactory) newShardBlockProcessor( } argsNewTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: pcf.state.AccountsAdapter(), - Hasher: pcf.coreData.Hasher(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - SignMarshalizer: pcf.coreData.TxMarshalizer(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScProcessor: scProcessorProxy, - TxFeeHandler: txFeeHandler, - TxTypeHandler: txTypeHandler, - EconomicsFee: pcf.coreData.EconomicsData(), - ReceiptForwarder: receiptTxInterim, - BadTxForwarder: badTxInterim, - ArgsParser: argsParser, - ScrForwarder: scForwarder, - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - GuardianChecker: pcf.bootstrapComponents.GuardedAccountHandler(), - TxVersionChecker: pcf.coreData.TxVersionChecker(), - TxLogsProcessor: pcf.txLogsProcessor, - RelayedTxV3Processor: relayedTxV3Processor, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + Accounts: pcf.state.AccountsAdapter(), + Hasher: pcf.coreData.Hasher(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + SignMarshalizer: pcf.coreData.TxMarshalizer(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScProcessor: scProcessorProxy, + TxFeeHandler: txFeeHandler, + TxTypeHandler: txTypeHandler, + EconomicsFee: pcf.coreData.EconomicsData(), + ReceiptForwarder: receiptTxInterim, + BadTxForwarder: badTxInterim, + ArgsParser: argsParser, + ScrForwarder: scForwarder, + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + GuardianChecker: pcf.bootstrapComponents.GuardedAccountHandler(), + TxVersionChecker: pcf.coreData.TxVersionChecker(), + TxLogsProcessor: pcf.txLogsProcessor, } transactionProcessor, err := transaction.NewTxProcessor(argsNewTxProcessor) if err != nil { @@ -570,11 +557,6 @@ func (pcf *processComponentsFactory) newMetaBlockProcessor( return nil, err } - err = pcf.coreData.EconomicsData().SetTxTypeHandler(txTypeHandler) - if err != nil { - return nil, err - } - gasHandler, err := preprocess.NewGasComputation( pcf.coreData.EconomicsData(), txTypeHandler, @@ -584,33 +566,31 @@ func (pcf *processComponentsFactory) newMetaBlockProcessor( return nil, err } - failedTxLogsAccumulator := transactionLog.NewFailedTxLogsAccumulator() txFeeHandler := postprocess.NewFeeAccumulator() enableEpochs := pcf.epochConfig.EnableEpochs argsNewScProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: argsParser, - Hasher: pcf.coreData.Hasher(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - AccountsDB: pcf.state.AccountsAdapter(), - BlockChainHook: vmFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScrForwarder: scForwarder, - TxFeeHandler: txFeeHandler, - EconomicsFee: pcf.coreData.EconomicsData(), - TxTypeHandler: txTypeHandler, - GasHandler: gasHandler, - GasSchedule: pcf.gasSchedule, - TxLogsProcessor: pcf.txLogsProcessor, - IsGenesisProcessing: false, - BadTxForwarder: badTxForwarder, - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: wasmVMChangeLocker, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + VmContainer: vmContainer, + ArgsParser: argsParser, + Hasher: pcf.coreData.Hasher(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + AccountsDB: pcf.state.AccountsAdapter(), + BlockChainHook: vmFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScrForwarder: scForwarder, + TxFeeHandler: txFeeHandler, + EconomicsFee: pcf.coreData.EconomicsData(), + TxTypeHandler: txTypeHandler, + GasHandler: gasHandler, + GasSchedule: pcf.gasSchedule, + TxLogsProcessor: pcf.txLogsProcessor, + IsGenesisProcessing: false, + BadTxForwarder: badTxForwarder, + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: wasmVMChangeLocker, } scProcessorProxy, err := processProxy.NewSmartContractProcessorProxy(argsNewScProcessor, pcf.epochNotifier) diff --git a/factory/processing/blockProcessorCreator_test.go b/factory/processing/blockProcessorCreator_test.go index 4fb8f8c5d7d..099fec4a82d 100644 --- a/factory/processing/blockProcessorCreator_test.go +++ b/factory/processing/blockProcessorCreator_test.go @@ -57,7 +57,6 @@ func Test_newBlockProcessorCreatorForShard(t *testing.T) { &testscommon.BlockProcessingCutoffStub{}, &testscommon.MissingTrieNodesNotifierStub{}, &testscommon.SentSignatureTrackerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) require.NoError(t, err) @@ -185,7 +184,6 @@ func Test_newBlockProcessorCreatorForMeta(t *testing.T) { &testscommon.BlockProcessingCutoffStub{}, &testscommon.MissingTrieNodesNotifierStub{}, &testscommon.SentSignatureTrackerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) require.NoError(t, err) diff --git a/factory/processing/export_test.go b/factory/processing/export_test.go index c82f01b3f6f..76e84d75fee 100644 --- a/factory/processing/export_test.go +++ b/factory/processing/export_test.go @@ -25,7 +25,6 @@ func (pcf *processComponentsFactory) NewBlockProcessor( blockProcessingCutoff cutoff.BlockProcessingCutoffHandler, missingTrieNodesNotifier common.MissingTrieNodesNotifier, sentSignaturesTracker process.SentSignaturesTracker, - relayedV3TxProcessor process.RelayedTxV3Processor, ) (process.BlockProcessor, process.EpochStartSystemSCProcessor, error) { blockProcessorComponents, err := pcf.newBlockProcessor( requestHandler, @@ -43,7 +42,6 @@ func (pcf *processComponentsFactory) NewBlockProcessor( blockProcessingCutoff, missingTrieNodesNotifier, sentSignaturesTracker, - relayedV3TxProcessor, ) if err != nil { return nil, nil, err @@ -53,6 +51,6 @@ func (pcf *processComponentsFactory) NewBlockProcessor( } // CreateAPITransactionEvaluator - -func (pcf *processComponentsFactory) CreateAPITransactionEvaluator(relayedV3TxProcessor process.RelayedTxV3Processor) (factory.TransactionEvaluator, process.VirtualMachinesContainerFactory, error) { - return pcf.createAPITransactionEvaluator(relayedV3TxProcessor) +func (pcf *processComponentsFactory) CreateAPITransactionEvaluator() (factory.TransactionEvaluator, process.VirtualMachinesContainerFactory, error) { + return pcf.createAPITransactionEvaluator() } diff --git a/factory/processing/processComponents.go b/factory/processing/processComponents.go index 6f711a502ae..482343bbadf 100644 --- a/factory/processing/processComponents.go +++ b/factory/processing/processComponents.go @@ -62,7 +62,6 @@ import ( "github.com/multiversx/mx-chain-go/process/smartContract" "github.com/multiversx/mx-chain-go/process/sync" "github.com/multiversx/mx-chain-go/process/track" - "github.com/multiversx/mx-chain-go/process/transaction" "github.com/multiversx/mx-chain-go/process/transactionLog" "github.com/multiversx/mx-chain-go/process/txsSender" "github.com/multiversx/mx-chain-go/redundancy" @@ -134,7 +133,6 @@ type processComponents struct { receiptsRepository mainFactory.ReceiptsRepository sentSignaturesTracker process.SentSignaturesTracker epochSystemSCProcessor process.EpochStartSystemSCProcessor - relayedTxV3Processor process.RelayedTxV3Processor } // ProcessComponentsFactoryArgs holds the arguments needed to create a process components factory @@ -517,16 +515,6 @@ func (pcf *processComponentsFactory) Create() (*processComponents, error) { return nil, err } - argsRelayedTxV3Processor := transaction.ArgRelayedTxV3Processor{ - EconomicsFee: pcf.coreData.EconomicsData(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - MaxTransactionsAllowed: pcf.config.RelayedTransactionConfig.MaxTransactionsAllowed, - } - relayedTxV3Processor, err := transaction.NewRelayedTxV3Processor(argsRelayedTxV3Processor) - if err != nil { - return nil, err - } - interceptorContainerFactory, blackListHandler, err := pcf.newInterceptorContainerFactory( headerSigVerifier, pcf.bootstrapComponents.HeaderIntegrityVerifier(), @@ -536,7 +524,6 @@ func (pcf *processComponentsFactory) Create() (*processComponents, error) { mainPeerShardMapper, fullArchivePeerShardMapper, hardforkTrigger, - relayedTxV3Processor, ) if err != nil { return nil, err @@ -633,7 +620,6 @@ func (pcf *processComponentsFactory) Create() (*processComponents, error) { blockCutoffProcessingHandler, pcf.state.MissingTrieNodesNotifier(), sentSignaturesTracker, - relayedTxV3Processor, ) if err != nil { return nil, err @@ -723,7 +709,7 @@ func (pcf *processComponentsFactory) Create() (*processComponents, error) { return nil, err } - apiTransactionEvaluator, vmFactoryForTxSimulate, err := pcf.createAPITransactionEvaluator(relayedTxV3Processor) + apiTransactionEvaluator, vmFactoryForTxSimulate, err := pcf.createAPITransactionEvaluator() if err != nil { return nil, fmt.Errorf("%w when assembling components for the transactions simulator processor", err) } @@ -776,7 +762,6 @@ func (pcf *processComponentsFactory) Create() (*processComponents, error) { accountsParser: pcf.accountsParser, receiptsRepository: receiptsRepository, sentSignaturesTracker: sentSignaturesTracker, - relayedTxV3Processor: relayedTxV3Processor, }, nil } @@ -1508,7 +1493,6 @@ func (pcf *processComponentsFactory) newInterceptorContainerFactory( mainPeerShardMapper *networksharding.PeerShardMapper, fullArchivePeerShardMapper *networksharding.PeerShardMapper, hardforkTrigger factory.HardforkTrigger, - relayedTxV3Processor process.RelayedTxV3Processor, ) (process.InterceptorsContainerFactory, process.TimeCacher, error) { nodeOperationMode := common.NormalOperation if pcf.prefConfigs.Preferences.FullArchive { @@ -1527,7 +1511,6 @@ func (pcf *processComponentsFactory) newInterceptorContainerFactory( fullArchivePeerShardMapper, hardforkTrigger, nodeOperationMode, - relayedTxV3Processor, ) } if shardCoordinator.SelfId() == core.MetachainShardId { @@ -1541,7 +1524,6 @@ func (pcf *processComponentsFactory) newInterceptorContainerFactory( fullArchivePeerShardMapper, hardforkTrigger, nodeOperationMode, - relayedTxV3Processor, ) } @@ -1681,7 +1663,6 @@ func (pcf *processComponentsFactory) newShardInterceptorContainerFactory( fullArchivePeerShardMapper *networksharding.PeerShardMapper, hardforkTrigger factory.HardforkTrigger, nodeOperationMode common.NodeOperation, - relayedTxV3Processor process.RelayedTxV3Processor, ) (process.InterceptorsContainerFactory, process.TimeCacher, error) { headerBlackList := cache.NewTimeCache(timeSpanForBadHeaders) shardInterceptorsContainerFactoryArgs := interceptorscontainer.CommonInterceptorsContainerFactoryArgs{ @@ -1715,7 +1696,6 @@ func (pcf *processComponentsFactory) newShardInterceptorContainerFactory( FullArchivePeerShardMapper: fullArchivePeerShardMapper, HardforkTrigger: hardforkTrigger, NodeOperationMode: nodeOperationMode, - RelayedTxV3Processor: relayedTxV3Processor, } interceptorContainerFactory, err := interceptorscontainer.NewShardInterceptorsContainerFactory(shardInterceptorsContainerFactoryArgs) @@ -1736,7 +1716,6 @@ func (pcf *processComponentsFactory) newMetaInterceptorContainerFactory( fullArchivePeerShardMapper *networksharding.PeerShardMapper, hardforkTrigger factory.HardforkTrigger, nodeOperationMode common.NodeOperation, - relayedTxV3Processor process.RelayedTxV3Processor, ) (process.InterceptorsContainerFactory, process.TimeCacher, error) { headerBlackList := cache.NewTimeCache(timeSpanForBadHeaders) metaInterceptorsContainerFactoryArgs := interceptorscontainer.CommonInterceptorsContainerFactoryArgs{ @@ -1770,7 +1749,6 @@ func (pcf *processComponentsFactory) newMetaInterceptorContainerFactory( FullArchivePeerShardMapper: fullArchivePeerShardMapper, HardforkTrigger: hardforkTrigger, NodeOperationMode: nodeOperationMode, - RelayedTxV3Processor: relayedTxV3Processor, } interceptorContainerFactory, err := interceptorscontainer.NewMetaInterceptorsContainerFactory(metaInterceptorsContainerFactoryArgs) diff --git a/factory/processing/processComponentsHandler.go b/factory/processing/processComponentsHandler.go index 94f21a5b8f2..28b3c4b0eed 100644 --- a/factory/processing/processComponentsHandler.go +++ b/factory/processing/processComponentsHandler.go @@ -180,9 +180,6 @@ func (m *managedProcessComponents) CheckSubcomponents() error { if check.IfNil(m.processComponents.epochSystemSCProcessor) { return errors.ErrNilEpochSystemSCProcessor } - if check.IfNil(m.processComponents.relayedTxV3Processor) { - return errors.ErrNilRelayedTxV3Processor - } return nil } @@ -691,18 +688,6 @@ func (m *managedProcessComponents) EpochSystemSCProcessor() process.EpochStartSy return m.processComponents.epochSystemSCProcessor } -// RelayedTxV3Processor returns the relayed tx v3 processor -func (m *managedProcessComponents) RelayedTxV3Processor() process.RelayedTxV3Processor { - m.mutProcessComponents.RLock() - defer m.mutProcessComponents.RUnlock() - - if m.processComponents == nil { - return nil - } - - return m.processComponents.relayedTxV3Processor -} - // IsInterfaceNil returns true if the interface is nil func (m *managedProcessComponents) IsInterfaceNil() bool { return m == nil diff --git a/factory/processing/processComponentsHandler_test.go b/factory/processing/processComponentsHandler_test.go index c999d25b041..2aec3cb8c6e 100644 --- a/factory/processing/processComponentsHandler_test.go +++ b/factory/processing/processComponentsHandler_test.go @@ -94,7 +94,6 @@ func TestManagedProcessComponents_Create(t *testing.T) { require.True(t, check.IfNil(managedProcessComponents.FullArchiveInterceptorsContainer())) require.True(t, check.IfNil(managedProcessComponents.SentSignaturesTracker())) require.True(t, check.IfNil(managedProcessComponents.EpochSystemSCProcessor())) - require.True(t, check.IfNil(managedProcessComponents.RelayedTxV3Processor())) err := managedProcessComponents.Create() require.NoError(t, err) @@ -140,7 +139,6 @@ func TestManagedProcessComponents_Create(t *testing.T) { require.False(t, check.IfNil(managedProcessComponents.FullArchiveInterceptorsContainer())) require.False(t, check.IfNil(managedProcessComponents.SentSignaturesTracker())) require.False(t, check.IfNil(managedProcessComponents.EpochSystemSCProcessor())) - require.False(t, check.IfNil(managedProcessComponents.RelayedTxV3Processor())) require.Equal(t, factory.ProcessComponentsName, managedProcessComponents.String()) }) diff --git a/factory/processing/txSimulatorProcessComponents.go b/factory/processing/txSimulatorProcessComponents.go index 21fe2ddc073..257a46af1a5 100644 --- a/factory/processing/txSimulatorProcessComponents.go +++ b/factory/processing/txSimulatorProcessComponents.go @@ -27,7 +27,7 @@ import ( datafield "github.com/multiversx/mx-chain-vm-common-go/parsers/dataField" ) -func (pcf *processComponentsFactory) createAPITransactionEvaluator(relayedTxV3Processor process.RelayedTxV3Processor) (factory.TransactionEvaluator, process.VirtualMachinesContainerFactory, error) { +func (pcf *processComponentsFactory) createAPITransactionEvaluator() (factory.TransactionEvaluator, process.VirtualMachinesContainerFactory, error) { simulationAccountsDB, err := transactionEvaluator.NewSimulationAccountsDB(pcf.state.AccountsAdapterAPI()) if err != nil { return nil, nil, err @@ -47,7 +47,7 @@ func (pcf *processComponentsFactory) createAPITransactionEvaluator(relayedTxV3Pr return nil, nil, err } - txSimulatorProcessorArgs, vmContainerFactory, txTypeHandler, err := pcf.createArgsTxSimulatorProcessor(simulationAccountsDB, vmOutputCacher, txLogsProcessor, relayedTxV3Processor) + txSimulatorProcessorArgs, vmContainerFactory, txTypeHandler, err := pcf.createArgsTxSimulatorProcessor(simulationAccountsDB, vmOutputCacher, txLogsProcessor) if err != nil { return nil, nil, err } @@ -89,13 +89,12 @@ func (pcf *processComponentsFactory) createArgsTxSimulatorProcessor( accountsAdapter state.AccountsAdapter, vmOutputCacher storage.Cacher, txLogsProcessor process.TransactionLogProcessor, - relayedTxV3Processor process.RelayedTxV3Processor, ) (transactionEvaluator.ArgsTxSimulator, process.VirtualMachinesContainerFactory, process.TxTypeHandler, error) { shardID := pcf.bootstrapComponents.ShardCoordinator().SelfId() if shardID == core.MetachainShardId { return pcf.createArgsTxSimulatorProcessorForMeta(accountsAdapter, vmOutputCacher, txLogsProcessor) } else { - return pcf.createArgsTxSimulatorProcessorShard(accountsAdapter, vmOutputCacher, txLogsProcessor, relayedTxV3Processor) + return pcf.createArgsTxSimulatorProcessorShard(accountsAdapter, vmOutputCacher, txLogsProcessor) } } @@ -173,32 +172,29 @@ func (pcf *processComponentsFactory) createArgsTxSimulatorProcessorForMeta( return args, nil, nil, err } - failedTxLogsAccumulator := transactionLog.NewFailedTxLogsAccumulator() - scProcArgs := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: smartContract.NewArgumentParser(), - Hasher: pcf.coreData.Hasher(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - AccountsDB: accountsAdapter, - BlockChainHook: vmContainerFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScrForwarder: scForwarder, - TxFeeHandler: &processDisabled.FeeHandler{}, - EconomicsFee: pcf.coreData.EconomicsData(), - TxTypeHandler: txTypeHandler, - GasHandler: gasHandler, - GasSchedule: pcf.gasSchedule, - TxLogsProcessor: txLogsProcessor, - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - BadTxForwarder: badTxInterim, - VMOutputCacher: vmOutputCacher, - WasmVMChangeLocker: pcf.coreData.WasmVMChangeLocker(), - IsGenesisProcessing: false, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + VmContainer: vmContainer, + ArgsParser: smartContract.NewArgumentParser(), + Hasher: pcf.coreData.Hasher(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + AccountsDB: accountsAdapter, + BlockChainHook: vmContainerFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScrForwarder: scForwarder, + TxFeeHandler: &processDisabled.FeeHandler{}, + EconomicsFee: pcf.coreData.EconomicsData(), + TxTypeHandler: txTypeHandler, + GasHandler: gasHandler, + GasSchedule: pcf.gasSchedule, + TxLogsProcessor: txLogsProcessor, + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + BadTxForwarder: badTxInterim, + VMOutputCacher: vmOutputCacher, + WasmVMChangeLocker: pcf.coreData.WasmVMChangeLocker(), + IsGenesisProcessing: false, } scProcessor, err := smartContract.NewSmartContractProcessor(scProcArgs) @@ -253,7 +249,6 @@ func (pcf *processComponentsFactory) createArgsTxSimulatorProcessorShard( accountsAdapter state.AccountsAdapter, vmOutputCacher storage.Cacher, txLogsProcessor process.TransactionLogProcessor, - relayedTxV3Processor process.RelayedTxV3Processor, ) (transactionEvaluator.ArgsTxSimulator, process.VirtualMachinesContainerFactory, process.TxTypeHandler, error) { args := transactionEvaluator.ArgsTxSimulator{} @@ -351,32 +346,29 @@ func (pcf *processComponentsFactory) createArgsTxSimulatorProcessorShard( argsParser := smartContract.NewArgumentParser() - failedTxLogsAccumulator := transactionLog.NewFailedTxLogsAccumulator() - scProcArgs := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: argsParser, - Hasher: pcf.coreData.Hasher(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - AccountsDB: accountsAdapter, - BlockChainHook: vmContainerFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScrForwarder: scForwarder, - TxFeeHandler: &processDisabled.FeeHandler{}, - EconomicsFee: pcf.coreData.EconomicsData(), - TxTypeHandler: txTypeHandler, - GasHandler: gasHandler, - GasSchedule: pcf.gasSchedule, - TxLogsProcessor: txLogsProcessor, - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - BadTxForwarder: badTxInterim, - VMOutputCacher: vmOutputCacher, - WasmVMChangeLocker: pcf.coreData.WasmVMChangeLocker(), - IsGenesisProcessing: false, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + VmContainer: vmContainer, + ArgsParser: argsParser, + Hasher: pcf.coreData.Hasher(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + AccountsDB: accountsAdapter, + BlockChainHook: vmContainerFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScrForwarder: scForwarder, + TxFeeHandler: &processDisabled.FeeHandler{}, + EconomicsFee: pcf.coreData.EconomicsData(), + TxTypeHandler: txTypeHandler, + GasHandler: gasHandler, + GasSchedule: pcf.gasSchedule, + TxLogsProcessor: txLogsProcessor, + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + BadTxForwarder: badTxInterim, + VMOutputCacher: vmOutputCacher, + WasmVMChangeLocker: pcf.coreData.WasmVMChangeLocker(), + IsGenesisProcessing: false, } scProcessor, err := smartContract.NewSmartContractProcessor(scProcArgs) @@ -385,27 +377,25 @@ func (pcf *processComponentsFactory) createArgsTxSimulatorProcessorShard( } argsTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: accountsAdapter, - Hasher: pcf.coreData.Hasher(), - PubkeyConv: pcf.coreData.AddressPubKeyConverter(), - Marshalizer: pcf.coreData.InternalMarshalizer(), - SignMarshalizer: pcf.coreData.TxMarshalizer(), - ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), - ScProcessor: scProcessor, - TxFeeHandler: txFeeHandler, - TxTypeHandler: txTypeHandler, - EconomicsFee: pcf.coreData.EconomicsData(), - ReceiptForwarder: receiptTxInterim, - BadTxForwarder: badTxInterim, - ArgsParser: argsParser, - ScrForwarder: scForwarder, - EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), - EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), - TxVersionChecker: pcf.coreData.TxVersionChecker(), - GuardianChecker: pcf.bootstrapComponents.GuardedAccountHandler(), - TxLogsProcessor: txLogsProcessor, - RelayedTxV3Processor: relayedTxV3Processor, - FailedTxLogsAccumulator: failedTxLogsAccumulator, + Accounts: accountsAdapter, + Hasher: pcf.coreData.Hasher(), + PubkeyConv: pcf.coreData.AddressPubKeyConverter(), + Marshalizer: pcf.coreData.InternalMarshalizer(), + SignMarshalizer: pcf.coreData.TxMarshalizer(), + ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), + ScProcessor: scProcessor, + TxFeeHandler: txFeeHandler, + TxTypeHandler: txTypeHandler, + EconomicsFee: pcf.coreData.EconomicsData(), + ReceiptForwarder: receiptTxInterim, + BadTxForwarder: badTxInterim, + ArgsParser: argsParser, + ScrForwarder: scForwarder, + EnableEpochsHandler: pcf.coreData.EnableEpochsHandler(), + EnableRoundsHandler: pcf.coreData.EnableRoundsHandler(), + TxVersionChecker: pcf.coreData.TxVersionChecker(), + GuardianChecker: pcf.bootstrapComponents.GuardedAccountHandler(), + TxLogsProcessor: txLogsProcessor, } txProcessor, err := transaction.NewTxProcessor(argsTxProcessor) diff --git a/factory/processing/txSimulatorProcessComponents_test.go b/factory/processing/txSimulatorProcessComponents_test.go index 37944768bfe..aad848600d8 100644 --- a/factory/processing/txSimulatorProcessComponents_test.go +++ b/factory/processing/txSimulatorProcessComponents_test.go @@ -8,7 +8,6 @@ import ( "github.com/multiversx/mx-chain-go/factory/processing" "github.com/multiversx/mx-chain-go/process/mock" "github.com/multiversx/mx-chain-go/testscommon/components" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/stretchr/testify/assert" ) @@ -27,7 +26,7 @@ func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { processArgs.Config.VMOutputCacher.Type = "invalid" pcf, _ := processing.NewProcessComponentsFactory(processArgs) - apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator(&processMocks.RelayedTxV3ProcessorMock{}) + apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator() assert.NotNil(t, err) assert.True(t, check.IfNil(apiTransactionEvaluator)) assert.True(t, check.IfNil(vmContainerFactory)) @@ -37,7 +36,7 @@ func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { processArgs := components.GetProcessComponentsFactoryArgs(shardCoordinatorForShardID2) pcf, _ := processing.NewProcessComponentsFactory(processArgs) - apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator(&processMocks.RelayedTxV3ProcessorMock{}) + apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator() assert.Nil(t, err) assert.False(t, check.IfNil(apiTransactionEvaluator)) assert.False(t, check.IfNil(vmContainerFactory)) @@ -46,7 +45,7 @@ func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { processArgs := components.GetProcessComponentsFactoryArgs(shardCoordinatorForMetachain) pcf, _ := processing.NewProcessComponentsFactory(processArgs) - apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator(&processMocks.RelayedTxV3ProcessorMock{}) + apiTransactionEvaluator, vmContainerFactory, err := pcf.CreateAPITransactionEvaluator() assert.Nil(t, err) assert.False(t, check.IfNil(apiTransactionEvaluator)) assert.False(t, check.IfNil(vmContainerFactory)) diff --git a/genesis/process/disabled/feeHandler.go b/genesis/process/disabled/feeHandler.go index f81e7e978eb..1fc34bbc2b5 100644 --- a/genesis/process/disabled/feeHandler.go +++ b/genesis/process/disabled/feeHandler.go @@ -183,11 +183,6 @@ func (fh *FeeHandler) ComputeTxFeeBasedOnGasUsedInEpoch(tx data.TransactionWithF return big.NewInt(0) } -// ComputeRelayedTxFees returns 0 and 0 -func (fh *FeeHandler) ComputeRelayedTxFees(_ data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil -} - // IsInterfaceNil returns true if there is no value under the interface func (fh *FeeHandler) IsInterfaceNil() bool { return fh == nil diff --git a/genesis/process/metaGenesisBlockCreator.go b/genesis/process/metaGenesisBlockCreator.go index 78546562736..f695c274b42 100644 --- a/genesis/process/metaGenesisBlockCreator.go +++ b/genesis/process/metaGenesisBlockCreator.go @@ -28,7 +28,6 @@ import ( "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/process/block/preprocess" "github.com/multiversx/mx-chain-go/process/coordinator" - disabledProcess "github.com/multiversx/mx-chain-go/process/disabled" "github.com/multiversx/mx-chain-go/process/factory" "github.com/multiversx/mx-chain-go/process/factory/metachain" disabledGuardian "github.com/multiversx/mx-chain-go/process/guardian/disabled" @@ -431,11 +430,6 @@ func createProcessorsForMetaGenesisBlock(arg ArgsGenesisBlockCreator, enableEpoc return nil, err } - err = arg.Core.EconomicsData().SetTxTypeHandler(txTypeHandler) - if err != nil { - return nil, err - } - gasHandler, err := preprocess.NewGasComputation(arg.Economics, txTypeHandler, enableEpochsHandler) if err != nil { return nil, err @@ -443,29 +437,28 @@ func createProcessorsForMetaGenesisBlock(arg ArgsGenesisBlockCreator, enableEpoc argsParser := smartContract.NewArgumentParser() argsNewSCProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: argsParser, - Hasher: arg.Core.Hasher(), - Marshalizer: arg.Core.InternalMarshalizer(), - AccountsDB: arg.Accounts, - BlockChainHook: virtualMachineFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncs, - PubkeyConv: arg.Core.AddressPubKeyConverter(), - ShardCoordinator: arg.ShardCoordinator, - ScrForwarder: scForwarder, - TxFeeHandler: genesisFeeHandler, - EconomicsFee: genesisFeeHandler, - TxTypeHandler: txTypeHandler, - GasHandler: gasHandler, - GasSchedule: arg.GasSchedule, - TxLogsProcessor: arg.TxLogsProcessor, - BadTxForwarder: badTxForwarder, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - IsGenesisProcessing: true, - WasmVMChangeLocker: &sync.RWMutex{}, // local Locker as to not interfere with the rest of the components - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: disabledProcess.NewFailedTxLogsAccumulator(), + VmContainer: vmContainer, + ArgsParser: argsParser, + Hasher: arg.Core.Hasher(), + Marshalizer: arg.Core.InternalMarshalizer(), + AccountsDB: arg.Accounts, + BlockChainHook: virtualMachineFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncs, + PubkeyConv: arg.Core.AddressPubKeyConverter(), + ShardCoordinator: arg.ShardCoordinator, + ScrForwarder: scForwarder, + TxFeeHandler: genesisFeeHandler, + EconomicsFee: genesisFeeHandler, + TxTypeHandler: txTypeHandler, + GasHandler: gasHandler, + GasSchedule: arg.GasSchedule, + TxLogsProcessor: arg.TxLogsProcessor, + BadTxForwarder: badTxForwarder, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + IsGenesisProcessing: true, + WasmVMChangeLocker: &sync.RWMutex{}, // local Locker as to not interfere with the rest of the components + VMOutputCacher: txcache.NewDisabledCache(), } scProcessorProxy, err := processProxy.NewSmartContractProcessorProxy(argsNewSCProcessor, epochNotifier) diff --git a/genesis/process/shardGenesisBlockCreator.go b/genesis/process/shardGenesisBlockCreator.go index b44ed14c207..2347632d2d5 100644 --- a/genesis/process/shardGenesisBlockCreator.go +++ b/genesis/process/shardGenesisBlockCreator.go @@ -24,7 +24,6 @@ import ( "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/process/block/preprocess" "github.com/multiversx/mx-chain-go/process/coordinator" - processDisabled "github.com/multiversx/mx-chain-go/process/disabled" "github.com/multiversx/mx-chain-go/process/factory/shard" disabledGuardian "github.com/multiversx/mx-chain-go/process/guardian/disabled" "github.com/multiversx/mx-chain-go/process/receipts" @@ -501,40 +500,34 @@ func createProcessorsForShardGenesisBlock(arg ArgsGenesisBlockCreator, enableEpo return nil, err } - err = arg.Core.EconomicsData().SetTxTypeHandler(txTypeHandler) - if err != nil { - return nil, err - } - gasHandler, err := preprocess.NewGasComputation(arg.Economics, txTypeHandler, enableEpochsHandler) if err != nil { return nil, err } argsNewScProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: smartContract.NewArgumentParser(), - Hasher: arg.Core.Hasher(), - Marshalizer: arg.Core.InternalMarshalizer(), - AccountsDB: arg.Accounts, - BlockChainHook: vmFactoryImpl.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: arg.Core.AddressPubKeyConverter(), - ShardCoordinator: arg.ShardCoordinator, - ScrForwarder: scForwarder, - TxFeeHandler: genesisFeeHandler, - EconomicsFee: genesisFeeHandler, - TxTypeHandler: txTypeHandler, - GasHandler: gasHandler, - GasSchedule: arg.GasSchedule, - TxLogsProcessor: arg.TxLogsProcessor, - BadTxForwarder: badTxInterim, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - IsGenesisProcessing: true, - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: genesisWasmVMLocker, - FailedTxLogsAccumulator: processDisabled.NewFailedTxLogsAccumulator(), + VmContainer: vmContainer, + ArgsParser: smartContract.NewArgumentParser(), + Hasher: arg.Core.Hasher(), + Marshalizer: arg.Core.InternalMarshalizer(), + AccountsDB: arg.Accounts, + BlockChainHook: vmFactoryImpl.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: arg.Core.AddressPubKeyConverter(), + ShardCoordinator: arg.ShardCoordinator, + ScrForwarder: scForwarder, + TxFeeHandler: genesisFeeHandler, + EconomicsFee: genesisFeeHandler, + TxTypeHandler: txTypeHandler, + GasHandler: gasHandler, + GasSchedule: arg.GasSchedule, + TxLogsProcessor: arg.TxLogsProcessor, + BadTxForwarder: badTxInterim, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + IsGenesisProcessing: true, + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: genesisWasmVMLocker, } scProcessorProxy, err := processProxy.NewSmartContractProcessorProxy(argsNewScProcessor, epochNotifier) @@ -552,27 +545,25 @@ func createProcessorsForShardGenesisBlock(arg ArgsGenesisBlockCreator, enableEpo } argsNewTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: arg.Accounts, - Hasher: arg.Core.Hasher(), - PubkeyConv: arg.Core.AddressPubKeyConverter(), - Marshalizer: arg.Core.InternalMarshalizer(), - SignMarshalizer: arg.Core.TxMarshalizer(), - ShardCoordinator: arg.ShardCoordinator, - ScProcessor: scProcessorProxy, - TxFeeHandler: genesisFeeHandler, - TxTypeHandler: txTypeHandler, - EconomicsFee: genesisFeeHandler, - ReceiptForwarder: receiptTxInterim, - BadTxForwarder: badTxInterim, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: scForwarder, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - TxVersionChecker: arg.Core.TxVersionChecker(), - GuardianChecker: disabledGuardian.NewDisabledGuardedAccountHandler(), - TxLogsProcessor: arg.TxLogsProcessor, - RelayedTxV3Processor: processDisabled.NewRelayedTxV3Processor(), - FailedTxLogsAccumulator: processDisabled.NewFailedTxLogsAccumulator(), + Accounts: arg.Accounts, + Hasher: arg.Core.Hasher(), + PubkeyConv: arg.Core.AddressPubKeyConverter(), + Marshalizer: arg.Core.InternalMarshalizer(), + SignMarshalizer: arg.Core.TxMarshalizer(), + ShardCoordinator: arg.ShardCoordinator, + ScProcessor: scProcessorProxy, + TxFeeHandler: genesisFeeHandler, + TxTypeHandler: txTypeHandler, + EconomicsFee: genesisFeeHandler, + ReceiptForwarder: receiptTxInterim, + BadTxForwarder: badTxInterim, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: scForwarder, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + TxVersionChecker: arg.Core.TxVersionChecker(), + GuardianChecker: disabledGuardian.NewDisabledGuardedAccountHandler(), + TxLogsProcessor: arg.TxLogsProcessor, } transactionProcessor, err := transaction.NewTxProcessor(argsNewTxProcessor) if err != nil { diff --git a/go.mod b/go.mod index d2b76ce9593..8718f3e9d10 100644 --- a/go.mod +++ b/go.mod @@ -15,9 +15,9 @@ require ( github.com/klauspost/cpuid/v2 v2.2.5 github.com/mitchellh/mapstructure v1.5.0 github.com/multiversx/mx-chain-communication-go v1.1.0 - github.com/multiversx/mx-chain-core-go v1.2.22 + github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c github.com/multiversx/mx-chain-crypto-go v1.2.12 - github.com/multiversx/mx-chain-es-indexer-go v1.7.9 + github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6 github.com/multiversx/mx-chain-logger-go v1.0.15 github.com/multiversx/mx-chain-scenario-go v1.4.4 github.com/multiversx/mx-chain-storage-go v1.0.16 diff --git a/go.sum b/go.sum index 0b789eb79b2..232f91ed5a7 100644 --- a/go.sum +++ b/go.sum @@ -387,12 +387,12 @@ github.com/multiversx/concurrent-map v0.1.4 h1:hdnbM8VE4b0KYJaGY5yJS2aNIW9TFFsUY github.com/multiversx/concurrent-map v0.1.4/go.mod h1:8cWFRJDOrWHOTNSqgYCUvwT7c7eFQ4U2vKMOp4A/9+o= github.com/multiversx/mx-chain-communication-go v1.1.0 h1:J7bX6HoN3HiHY7cUeEjG8AJWgQDDPcY+OPDOsSUOkRE= github.com/multiversx/mx-chain-communication-go v1.1.0/go.mod h1:WK6bP4pGEHGDDna/AYRIMtl6G9OA0NByI1Lw8PmOnRM= -github.com/multiversx/mx-chain-core-go v1.2.22 h1:yDYrvoQOBbsDerEp7L3+de5AfMy3pTF333gWPpd+FNk= -github.com/multiversx/mx-chain-core-go v1.2.22/go.mod h1:B5zU4MFyJezmEzCsAHE9YNULmGCm2zbPHvl9hazNxmE= +github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c h1:hPCfMSj2vd9xNkARNxB1b3b9k8taFb+Xfja+WK97jno= +github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c/go.mod h1:B5zU4MFyJezmEzCsAHE9YNULmGCm2zbPHvl9hazNxmE= github.com/multiversx/mx-chain-crypto-go v1.2.12 h1:zWip7rpUS4CGthJxfKn5MZfMfYPjVjIiCID6uX5BSOk= github.com/multiversx/mx-chain-crypto-go v1.2.12/go.mod h1:HzcPpCm1zanNct/6h2rIh+MFrlXbjA5C8+uMyXj3LI4= -github.com/multiversx/mx-chain-es-indexer-go v1.7.9 h1:rWq9phJu8GG6TtoJ5cL+MmhyReWCEyqBE5ymXUvudCg= -github.com/multiversx/mx-chain-es-indexer-go v1.7.9/go.mod h1:oGcRK2E3Syv6vRTszWrrb/TqD8akq0yeoMr1wPPiTO4= +github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6 h1:2F5WyCIvFVs4CONd9kJxibY1NIfJLYFAwqNJvC31qNA= +github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6/go.mod h1:AJew7KVcICVyVDlXpDQzvjcSnKs0aCYl7eXnJwg+15E= github.com/multiversx/mx-chain-logger-go v1.0.15 h1:HlNdK8etyJyL9NQ+6mIXyKPEBo+wRqOwi3n+m2QIHXc= github.com/multiversx/mx-chain-logger-go v1.0.15/go.mod h1:t3PRKaWB1M+i6gUfD27KXgzLJJC+mAQiN+FLlL1yoGQ= github.com/multiversx/mx-chain-scenario-go v1.4.4 h1:DVE2V+FPeyD/yWoC+KEfPK3jsFzHeruelESfpTlf460= diff --git a/integrationTests/chainSimulator/relayedTx/relayedTx_test.go b/integrationTests/chainSimulator/relayedTx/relayedTx_test.go index fa2b02b9fe3..f7c0f74649b 100644 --- a/integrationTests/chainSimulator/relayedTx/relayedTx_test.go +++ b/integrationTests/chainSimulator/relayedTx/relayedTx_test.go @@ -4,7 +4,6 @@ import ( "encoding/hex" "encoding/json" "math/big" - "strconv" "strings" "testing" "time" @@ -18,9 +17,6 @@ import ( "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" - chainSimulatorProcess "github.com/multiversx/mx-chain-go/node/chainSimulator/process" - "github.com/multiversx/mx-chain-go/process" - "github.com/multiversx/mx-chain-go/sharding" "github.com/stretchr/testify/require" ) @@ -28,8 +24,6 @@ const ( defaultPathToInitialConfig = "../../../cmd/node/config/" minGasPrice = 1_000_000_000 minGasLimit = 50_000 - guardAccountCost = 250_000 - extraGasLimitForGuarded = minGasLimit gasPerDataByte = 1_500 txVersion = 2 mockTxSignature = "sig" @@ -38,383 +32,9 @@ const ( ) var ( - oneEGLD = big.NewInt(1000000000000000000) - alterConfigsFuncRelayedV3EarlyActivation = func(cfg *config.Configs) { - cfg.EpochConfig.EnableEpochs.RelayedTransactionsV3EnableEpoch = 1 - cfg.EpochConfig.EnableEpochs.FixRelayedBaseCostEnableEpoch = 1 - } + oneEGLD = big.NewInt(1000000000000000000) ) -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulator(t *testing.T) { - if testing.Short() { - t.Skip("this is not a short test") - } - - cs := startChainSimulator(t, alterConfigsFuncRelayedV3EarlyActivation) - defer cs.Close() - - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(30000)) - relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - sender, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - receiver, err := cs.GenerateAndMintWalletAddress(1, big.NewInt(0)) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - innerTx := generateTransaction(sender.Bytes, 0, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx.RelayerAddr = relayer.Bytes - - sender2, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - receiver2, err := cs.GenerateAndMintWalletAddress(0, big.NewInt(0)) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - innerTx2 := generateTransaction(sender2.Bytes, 0, receiver2.Bytes, oneEGLD, "", minGasLimit) - innerTx2.RelayerAddr = relayer.Bytes - - pkConv := cs.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter() - - // innerTx3Failure should fail due to less gas limit - // deploy a wrapper contract - owner, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - scCode := wasm.GetSCCode("testData/egld-esdt-swap.wasm") - params := []string{scCode, wasm.VMTypeHex, wasm.DummyCodeMetadataHex, hex.EncodeToString([]byte("WEGLD"))} - txDataDeploy := strings.Join(params, "@") - deployTx := generateTransaction(owner.Bytes, 0, make([]byte, 32), big.NewInt(0), txDataDeploy, 600000000) - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(deployTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - scAddress := result.Logs.Events[0].Address - scAddressBytes, _ := pkConv.Decode(scAddress) - - // try a wrap transaction which will fail as the contract is paused - txDataWrap := "wrapEgld" - gasLimit := 2300000 - innerTx3Failure := generateTransaction(owner.Bytes, 1, scAddressBytes, big.NewInt(1), txDataWrap, uint64(gasLimit)) - innerTx3Failure.RelayerAddr = relayer.Bytes - - innerTx3 := generateTransaction(sender.Bytes, 1, receiver2.Bytes, oneEGLD, "", minGasLimit) - innerTx3.RelayerAddr = relayer.Bytes - - innerTxs := []*transaction.Transaction{innerTx, innerTx2, innerTx3Failure, innerTx3} - - // relayer will consume first a move balance for each inner tx, then the specific gas for each inner tx - relayedTxGasLimit := uint64(0) - for _, tx := range innerTxs { - relayedTxGasLimit += minGasLimit + tx.GasLimit - } - relayedTx := generateTransaction(relayer.Bytes, 0, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - result, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // generate few more blocks for the cross shard scrs to be done - err = cs.GenerateBlocks(maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - economicsData := cs.GetNodeHandler(0).GetCoreComponents().EconomicsData() - relayerMoveBalanceFee := economicsData.ComputeMoveBalanceFee(relayedTx) - expectedRelayerFee := big.NewInt(0).Mul(relayerMoveBalanceFee, big.NewInt(int64(len(relayedTx.InnerTransactions)))) - for _, tx := range innerTxs { - expectedRelayerFee.Add(expectedRelayerFee, economicsData.ComputeTxFee(tx)) - } - checkBalance(t, cs, relayer, big.NewInt(0).Sub(initialBalance, expectedRelayerFee)) - - checkBalance(t, cs, sender, big.NewInt(0).Sub(initialBalance, big.NewInt(0).Mul(oneEGLD, big.NewInt(2)))) - - checkBalance(t, cs, sender2, big.NewInt(0).Sub(initialBalance, oneEGLD)) - - checkBalance(t, cs, receiver, oneEGLD) - - checkBalance(t, cs, receiver2, big.NewInt(0).Mul(oneEGLD, big.NewInt(2))) - - // check SCRs - shardC := cs.GetNodeHandler(0).GetShardCoordinator() - for _, scr := range result.SmartContractResults { - checkSCRSucceeded(t, cs, pkConv, shardC, scr) - } - - // 3 log events from the failed sc call - require.Equal(t, 3, len(result.Logs.Events)) - require.True(t, strings.Contains(string(result.Logs.Events[2].Data), "contract is paused")) -} - -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorAndInvalidNonces(t *testing.T) { - if testing.Short() { - t.Skip("this is not a short test") - } - - cs := startChainSimulator(t, alterConfigsFuncRelayedV3EarlyActivation) - defer cs.Close() - - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(30000)) - relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - sender, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - receiver, err := cs.GenerateAndMintWalletAddress(0, big.NewInt(0)) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - // bump sender nonce to 3 - tx0 := generateTransaction(sender.Bytes, 0, sender.Bytes, big.NewInt(0), "", minGasLimit) - tx1 := generateTransaction(sender.Bytes, 1, sender.Bytes, big.NewInt(0), "", minGasLimit) - tx2 := generateTransaction(sender.Bytes, 2, sender.Bytes, big.NewInt(0), "", minGasLimit) - _, err = cs.SendTxsAndGenerateBlocksTilAreExecuted([]*transaction.Transaction{tx0, tx1, tx2}, maxNumOfBlocksToGenerateWhenExecutingTx) - require.Nil(t, err) - - // higher nonce - innerTx1 := generateTransaction(sender.Bytes, 10, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx1.RelayerAddr = relayer.Bytes - - // higher nonce - innerTx2 := generateTransaction(sender.Bytes, 9, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx2.RelayerAddr = relayer.Bytes - - // nonce ok - innerTx3 := generateTransaction(sender.Bytes, 3, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx3.RelayerAddr = relayer.Bytes - - // higher nonce - innerTx4 := generateTransaction(sender.Bytes, 8, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx4.RelayerAddr = relayer.Bytes - - // lower nonce - initial one - innerTx5 := generateTransaction(sender.Bytes, 3, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx5.RelayerAddr = relayer.Bytes - - innerTxs := []*transaction.Transaction{innerTx1, innerTx2, innerTx3, innerTx4, innerTx5} - - // relayer will consume first a move balance for each inner tx, then the specific gas for each inner tx - relayedTxGasLimit := uint64(0) - for _, tx := range innerTxs { - relayedTxGasLimit += minGasLimit + tx.GasLimit - } - relayedTx := generateTransaction(relayer.Bytes, 0, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // 5 scrs, 4 from the failed txs + 1 with success - require.Equal(t, 5, len(result.SmartContractResults)) - scrsMap := make(map[string]int, len(result.SmartContractResults)) - for _, scr := range result.SmartContractResults { - if len(scr.ReturnMessage) == 0 { - scrsMap["success"]++ - } - if strings.Contains(scr.ReturnMessage, process.ErrHigherNonceInTransaction.Error()) { - scrsMap[process.ErrHigherNonceInTransaction.Error()]++ - } - if strings.Contains(scr.ReturnMessage, process.ErrLowerNonceInTransaction.Error()) { - scrsMap[process.ErrLowerNonceInTransaction.Error()]++ - } - } - require.Equal(t, 1, scrsMap["success"]) - require.Equal(t, 3, scrsMap[process.ErrHigherNonceInTransaction.Error()]) - require.Equal(t, 1, scrsMap[process.ErrLowerNonceInTransaction.Error()]) - - // 4 log events from the failed txs - require.Equal(t, 4, len(result.Logs.Events)) - for _, event := range result.Logs.Events { - require.Equal(t, core.SignalErrorOperation, event.Identifier) - } -} - -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorScCalls(t *testing.T) { - if testing.Short() { - t.Skip("this is not a short test") - } - - cs := startChainSimulator(t, alterConfigsFuncRelayedV3EarlyActivation) - defer cs.Close() - - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(10)) - relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - pkConv := cs.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter() - shardC := cs.GetNodeHandler(0).GetShardCoordinator() - - // deploy adder contract - owner, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - ownerNonce := uint64(0) - scAddressBytes := deployAdder(t, cs, owner, ownerNonce) - scShard := shardC.ComputeId(scAddressBytes) - scShardNodeHandler := cs.GetNodeHandler(scShard) - - // 1st inner tx, successful add 1 - ownerNonce++ - txDataAdd := "add@" + hex.EncodeToString(big.NewInt(1).Bytes()) - innerTx1 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), txDataAdd, 5000000) - innerTx1.RelayerAddr = relayer.Bytes - - // 2nd inner tx, successful add 1 - ownerNonce++ - innerTx2 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), txDataAdd, 5000000) - innerTx2.RelayerAddr = relayer.Bytes - - // 3rd inner tx, wrong number of parameters - ownerNonce++ - innerTx3 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), "add", 5000000) - innerTx3.RelayerAddr = relayer.Bytes - - // 4th inner tx, successful add 1 - ownerNonce++ - innerTx4 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), txDataAdd, 5000000) - innerTx4.RelayerAddr = relayer.Bytes - - // 5th inner tx, invalid function - ownerNonce++ - innerTx5 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), "substract", 5000000) - innerTx5.RelayerAddr = relayer.Bytes - - // 6th inner tx, successful add 1 - ownerNonce++ - innerTx6 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), txDataAdd, 5000000) - innerTx6.RelayerAddr = relayer.Bytes - - // 7th inner tx, not enough gas - ownerNonce++ - innerTx7 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, big.NewInt(0), txDataAdd, 100000) - innerTx7.RelayerAddr = relayer.Bytes - - innerTxs := []*transaction.Transaction{innerTx1, innerTx2, innerTx3, innerTx4, innerTx5, innerTx6, innerTx7} - - relayedTxGasLimit := uint64(0) - for _, tx := range innerTxs { - relayedTxGasLimit += minGasLimit + tx.GasLimit - } - relayedTx := generateTransaction(relayer.Bytes, 0, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - checkSum(t, scShardNodeHandler, scAddressBytes, owner.Bytes, 4) - - // 8 scrs, 4 from the succeeded txs + 4 with refunded gas to relayer - require.Equal(t, 8, len(result.SmartContractResults)) - for _, scr := range result.SmartContractResults { - if strings.Contains(scr.ReturnMessage, "gas refund for relayer") { - continue - } - - checkSCRSucceeded(t, cs, pkConv, shardC, scr) - } - - // 6 events, 3 with signalError + 3 with the actual errors - require.Equal(t, 6, len(result.Logs.Events)) - expectedLogEvents := map[int]string{ - 1: "[wrong number of arguments]", - 3: "[invalid function (not found)] [substract]", - 5: "[not enough gas] [add]", - } - for idx, logEvent := range result.Logs.Events { - if logEvent.Identifier == "signalError" { - continue - } - - expectedLogEvent := expectedLogEvents[idx] - require.True(t, strings.Contains(string(logEvent.Data), expectedLogEvent)) - } -} - -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorInnerMoveBalanceToNonPayableSC(t *testing.T) { - if testing.Short() { - t.Skip("this is not a short test") - } - - cs := startChainSimulator(t, func(cfg *config.Configs) { - cfg.EpochConfig.EnableEpochs.RelayedTransactionsV3EnableEpoch = 1 - cfg.EpochConfig.EnableEpochs.FixRelayedBaseCostEnableEpoch = 1 - cfg.EpochConfig.EnableEpochs.FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 1 - }) - defer cs.Close() - - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(10)) - relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - pkConv := cs.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter() - - // deploy adder contract - owner, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - ownerNonce := uint64(0) - scCode := wasm.GetSCCode("testData/adder.wasm") - params := []string{scCode, wasm.VMTypeHex, "0000", "00"} - txDataDeploy := strings.Join(params, "@") - deployTx := generateTransaction(owner.Bytes, ownerNonce, make([]byte, 32), big.NewInt(0), txDataDeploy, 100000000) - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(deployTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - scAddress := result.Logs.Events[0].Address - scAddressBytes, _ := pkConv.Decode(scAddress) - - balanceRelayerBefore := getBalance(t, cs, relayer) - balanceOwnerBefore := getBalance(t, cs, owner) - - // move balance to non-payable contract should only consume fees and sender's nonce - ownerNonce++ - innerTx1 := generateTransaction(owner.Bytes, ownerNonce, scAddressBytes, oneEGLD, "", 50000) - innerTx1.RelayerAddr = relayer.Bytes - - // move balance to meta contract should only consume fees and sender's nonce - ownerNonce++ - innerTx2 := generateTransaction(owner.Bytes, ownerNonce, core.ESDTSCAddress, oneEGLD, "", 50000) - innerTx2.RelayerAddr = relayer.Bytes - - innerTxs := []*transaction.Transaction{innerTx1, innerTx2} - - relayedTxGasLimit := uint64(0) - for _, tx := range innerTxs { - relayedTxGasLimit += minGasLimit + tx.GasLimit - } - relayedTx := generateTransaction(relayer.Bytes, 0, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - _, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - balanceRelayerAfter := getBalance(t, cs, relayer) - balanceOwnerAfter := getBalance(t, cs, owner) - consumedRelayedFee := core.SafeMul(relayedTxGasLimit, minGasPrice) - expectedBalanceRelayerAfter := big.NewInt(0).Sub(balanceRelayerBefore, consumedRelayedFee) - require.Equal(t, balanceOwnerBefore.String(), balanceOwnerAfter.String()) - require.Equal(t, expectedBalanceRelayerAfter.String(), balanceRelayerAfter.String()) -} - func TestFixRelayedMoveBalanceWithChainSimulator(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") @@ -594,131 +214,6 @@ func testFixRelayedMoveBalanceWithChainSimulatorMoveBalance( } } -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorInnerNotExecutable(t *testing.T) { - if testing.Short() { - t.Skip("this is not a short test") - } - - cs := startChainSimulator(t, alterConfigsFuncRelayedV3EarlyActivation) - defer cs.Close() - - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(10)) - relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - sender, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - sender2, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - guardian, err := cs.GenerateAndMintWalletAddress(0, initialBalance) - require.NoError(t, err) - - err = cs.GenerateBlocks(1) - require.Nil(t, err) - - // Set guardian for sender - senderNonce := uint64(0) - setGuardianTxData := "SetGuardian@" + hex.EncodeToString(guardian.Bytes) + "@" + hex.EncodeToString([]byte("uuid")) - setGuardianGasLimit := minGasLimit + 1500*len(setGuardianTxData) + guardAccountCost - setGuardianTx := generateTransaction(sender.Bytes, senderNonce, sender.Bytes, big.NewInt(0), setGuardianTxData, uint64(setGuardianGasLimit)) - _, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(setGuardianTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // fast-forward until the guardian becomes active - err = cs.GenerateBlocks(roundsPerEpoch * 20) - require.NoError(t, err) - - // guard account - senderNonce++ - guardAccountTxData := "GuardAccount" - guardAccountGasLimit := minGasLimit + 1500*len(guardAccountTxData) + guardAccountCost - guardAccountTx := generateTransaction(sender.Bytes, senderNonce, sender.Bytes, big.NewInt(0), guardAccountTxData, uint64(guardAccountGasLimit)) - _, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(guardAccountTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - receiver, err := cs.GenerateAndMintWalletAddress(1, big.NewInt(0)) - require.NoError(t, err) - - // move balance inner transaction non-executable due to guardian mismatch - senderNonce++ - innerTx := generateTransaction(sender.Bytes, senderNonce, receiver.Bytes, oneEGLD, "", minGasLimit+extraGasLimitForGuarded) - innerTx.RelayerAddr = relayer.Bytes - innerTx.GuardianAddr = sender.Bytes // this is not the real guardian - innerTx.GuardianSignature = []byte(mockTxSignature) - innerTx.Options = 2 - - // move balance inner transaction non-executable due to higher nonce - nonceTooHigh := uint64(100) - innerTx2 := generateTransaction(sender2.Bytes, nonceTooHigh, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx2.RelayerAddr = relayer.Bytes - - innerTxs := []*transaction.Transaction{innerTx, innerTx2} - - // relayer will consume first a move balance for each inner tx, then the specific gas for each inner tx - relayedTxGasLimit := uint64(0) - for _, tx := range innerTxs { - relayedTxGasLimit += minGasLimit + tx.GasLimit - } - relayedTx := generateTransaction(relayer.Bytes, 0, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // generate few more blocks for the cross shard scrs to be done - err = cs.GenerateBlocks(maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // check the inner tx failed with the desired error - require.Equal(t, 2, len(result.SmartContractResults)) - require.True(t, strings.Contains(result.SmartContractResults[0].ReturnMessage, process.ErrTransactionNotExecutable.Error())) - require.True(t, strings.Contains(result.SmartContractResults[0].ReturnMessage, process.ErrTransactionAndAccountGuardianMismatch.Error())) - require.True(t, strings.Contains(result.SmartContractResults[1].ReturnMessage, process.ErrHigherNonceInTransaction.Error())) - - // check events - require.Equal(t, 2, len(result.Logs.Events)) - for _, event := range result.Logs.Events { - require.Equal(t, core.SignalErrorOperation, event.Identifier) - } - - // compute expected consumed fee for relayer - expectedConsumedGasForGuardedInnerTx := minGasLimit + minGasLimit + extraGasLimitForGuarded // invalid guardian - expectedConsumedGasForHigherNonceInnerTx := minGasLimit + minGasLimit // higher nonce - expectedConsumeGas := expectedConsumedGasForGuardedInnerTx + expectedConsumedGasForHigherNonceInnerTx - expectedRelayerFee := core.SafeMul(uint64(expectedConsumeGas), minGasPrice) - checkBalance(t, cs, relayer, big.NewInt(0).Sub(initialBalance, expectedRelayerFee)) - - checkBalance(t, cs, receiver, big.NewInt(0)) - - relayerBalanceBeforeSuccessfullAttempt := getBalance(t, cs, relayer) - - // generate a valid guarded move balance inner tx - // senderNonce would be the same, as previous failed tx didn't increase it(expected) - innerTx = generateTransaction(sender.Bytes, senderNonce, receiver.Bytes, oneEGLD, "", minGasLimit+extraGasLimitForGuarded) - innerTx.RelayerAddr = relayer.Bytes - innerTx.GuardianAddr = guardian.Bytes - innerTx.GuardianSignature = []byte(mockTxSignature) - innerTx.Options = 2 - - innerTxs = []*transaction.Transaction{innerTx} - relayedTx = generateTransaction(relayer.Bytes, 1, relayer.Bytes, big.NewInt(0), "", relayedTxGasLimit) - relayedTx.InnerTransactions = innerTxs - - _, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - // generate few more blocks for the cross shard scrs to be done - err = cs.GenerateBlocks(maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - - expectedRelayerFee = core.SafeMul(uint64(expectedConsumedGasForGuardedInnerTx), minGasPrice) - checkBalance(t, cs, relayer, big.NewInt(0).Sub(relayerBalanceBeforeSuccessfullAttempt, expectedRelayerFee)) - - checkBalance(t, cs, receiver, oneEGLD) -} - func TestRelayedTransactionFeeField(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") @@ -726,8 +221,6 @@ func TestRelayedTransactionFeeField(t *testing.T) { cs := startChainSimulator(t, func(cfg *config.Configs) { cfg.EpochConfig.EnableEpochs.RelayedTransactionsEnableEpoch = 1 - cfg.EpochConfig.EnableEpochs.RelayedTransactionsV2EnableEpoch = 1 - cfg.EpochConfig.EnableEpochs.RelayedTransactionsV3EnableEpoch = 1 cfg.EpochConfig.EnableEpochs.FixRelayedBaseCostEnableEpoch = 1 }) defer cs.Close() @@ -757,22 +250,6 @@ func TestRelayedTransactionFeeField(t *testing.T) { result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) require.NoError(t, err) - expectedFee := core.SafeMul(uint64(gasLimit), minGasPrice) - require.Equal(t, expectedFee.String(), result.Fee) - require.Equal(t, expectedFee.String(), result.InitiallyPaidFee) - require.Equal(t, uint64(gasLimit), result.GasUsed) - }) - t.Run("relayed v3", func(t *testing.T) { - innerTx := generateTransaction(sender.Bytes, 1, receiver.Bytes, oneEGLD, "", minGasLimit) - innerTx.RelayerAddr = relayer.Bytes - - gasLimit := minGasLimit + int(innerTx.GasLimit) - relayedTx := generateTransaction(relayer.Bytes, 1, relayer.Bytes, big.NewInt(0), "", uint64(gasLimit)) - relayedTx.InnerTransactions = []*transaction.Transaction{innerTx} - - result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) - expectedFee := core.SafeMul(uint64(gasLimit), minGasPrice) require.Equal(t, expectedFee.String(), result.Fee) require.Equal(t, expectedFee.String(), result.InitiallyPaidFee) @@ -829,58 +306,6 @@ func generateTransaction(sender []byte, nonce uint64, receiver []byte, value *bi } } -func checkSum( - t *testing.T, - nodeHandler chainSimulatorProcess.NodeHandler, - scAddress []byte, - callerAddress []byte, - expectedSum int, -) { - scQuery := &process.SCQuery{ - ScAddress: scAddress, - FuncName: "getSum", - CallerAddr: callerAddress, - CallValue: big.NewInt(0), - } - result, _, err := nodeHandler.GetFacadeHandler().ExecuteSCQuery(scQuery) - require.Nil(t, err) - require.Equal(t, "ok", result.ReturnCode) - - sum, err := strconv.Atoi(hex.EncodeToString(result.ReturnData[0])) - require.NoError(t, err) - - require.Equal(t, expectedSum, sum) -} - -func checkSCRSucceeded( - t *testing.T, - cs testsChainSimulator.ChainSimulator, - pkConv core.PubkeyConverter, - shardC sharding.Coordinator, - scr *transaction.ApiSmartContractResult, -) { - addr, err := pkConv.Decode(scr.RcvAddr) - require.NoError(t, err) - - senderShard := shardC.ComputeId(addr) - tx, err := cs.GetNodeHandler(senderShard).GetFacadeHandler().GetTransaction(scr.Hash, true) - require.NoError(t, err) - require.Equal(t, transaction.TxStatusSuccess, tx.Status) - - if tx.ReturnMessage == core.GasRefundForRelayerMessage { - return - } - - require.GreaterOrEqual(t, len(tx.Logs.Events), 1) - for _, event := range tx.Logs.Events { - if event.Identifier == core.WriteLogIdentifier { - continue - } - - require.Equal(t, core.CompletedTxEventIdentifier, event.Identifier) - } -} - func getBalance( t *testing.T, cs testsChainSimulator.ChainSimulator, @@ -895,16 +320,6 @@ func getBalance( return balance } -func checkBalance( - t *testing.T, - cs testsChainSimulator.ChainSimulator, - address dtos.WalletAddress, - expectedBalance *big.Int, -) { - balance := getBalance(t, cs, address) - require.Equal(t, expectedBalance.String(), balance.String()) -} - func deployAdder( t *testing.T, cs testsChainSimulator.ChainSimulator, diff --git a/integrationTests/mock/processComponentsStub.go b/integrationTests/mock/processComponentsStub.go index 04dad00a52c..11d4f4ce69d 100644 --- a/integrationTests/mock/processComponentsStub.go +++ b/integrationTests/mock/processComponentsStub.go @@ -61,7 +61,6 @@ type ProcessComponentsStub struct { ESDTDataStorageHandlerForAPIInternal vmcommon.ESDTNFTStorageHandler SentSignaturesTrackerInternal process.SentSignaturesTracker EpochSystemSCProcessorInternal process.EpochStartSystemSCProcessor - RelayedTxV3ProcessorField process.RelayedTxV3Processor } // Create - @@ -303,11 +302,6 @@ func (pcs *ProcessComponentsStub) EpochSystemSCProcessor() process.EpochStartSys return pcs.EpochSystemSCProcessorInternal } -// RelayedTxV3Processor - -func (pcs *ProcessComponentsStub) RelayedTxV3Processor() process.RelayedTxV3Processor { - return pcs.RelayedTxV3ProcessorField -} - // IsInterfaceNil - func (pcs *ProcessComponentsStub) IsInterfaceNil() bool { return pcs == nil diff --git a/integrationTests/multiShard/relayedTx/common.go b/integrationTests/multiShard/relayedTx/common.go index 6815d12802e..54d99ff869d 100644 --- a/integrationTests/multiShard/relayedTx/common.go +++ b/integrationTests/multiShard/relayedTx/common.go @@ -19,7 +19,6 @@ func CreateGeneralSetupForRelayTxTest(relayedV3Test bool) ([]*integrationTests.T initialVal := big.NewInt(10000000000) epochsConfig := integrationTests.GetDefaultEnableEpochsConfig() if !relayedV3Test { - epochsConfig.RelayedTransactionsV3EnableEpoch = integrationTests.UnreachableEpoch epochsConfig.FixRelayedBaseCostEnableEpoch = integrationTests.UnreachableEpoch epochsConfig.FixRelayedMoveBalanceToNonPayableSCEnableEpoch = integrationTests.UnreachableEpoch } @@ -90,7 +89,7 @@ func CreateAndSendRelayedAndUserTx( ) (*transaction.Transaction, *transaction.Transaction) { txDispatcherNode := getNodeWithinSameShardAsPlayer(nodes, relayer.Address) - userTx := createUserTx(player, rcvAddr, value, gasLimit, txData, nil) + userTx := createUserTx(player, rcvAddr, value, gasLimit, txData) relayedTx := createRelayedTx(txDispatcherNode.EconomicsData, relayer, userTx) _, err := txDispatcherNode.SendTransaction(relayedTx) @@ -113,7 +112,7 @@ func CreateAndSendRelayedAndUserTxV2( ) (*transaction.Transaction, *transaction.Transaction) { txDispatcherNode := getNodeWithinSameShardAsPlayer(nodes, relayer.Address) - userTx := createUserTx(player, rcvAddr, value, 0, txData, nil) + userTx := createUserTx(player, rcvAddr, value, 0, txData) relayedTx := createRelayedTxV2(txDispatcherNode.EconomicsData, relayer, userTx, gasLimit) _, err := txDispatcherNode.SendTransaction(relayedTx) @@ -124,48 +123,23 @@ func CreateAndSendRelayedAndUserTxV2( return relayedTx, userTx } -// CreateAndSendRelayedAndUserTxV3 will create and send a relayed user transaction for relayed v3 -func CreateAndSendRelayedAndUserTxV3( - nodes []*integrationTests.TestProcessorNode, - relayer *integrationTests.TestWalletAccount, - player *integrationTests.TestWalletAccount, - rcvAddr []byte, - value *big.Int, - gasLimit uint64, - txData []byte, -) (*transaction.Transaction, *transaction.Transaction) { - txDispatcherNode := getNodeWithinSameShardAsPlayer(nodes, relayer.Address) - - userTx := createUserTx(player, rcvAddr, value, gasLimit, txData, relayer.Address) - relayedTx := createRelayedTxV3(txDispatcherNode.EconomicsData, relayer, userTx) - - _, err := txDispatcherNode.SendTransaction(relayedTx) - if err != nil { - fmt.Println(err.Error()) - } - - return relayedTx, userTx -} - func createUserTx( player *integrationTests.TestWalletAccount, rcvAddr []byte, value *big.Int, gasLimit uint64, txData []byte, - relayerAddress []byte, ) *transaction.Transaction { tx := &transaction.Transaction{ - Nonce: player.Nonce, - Value: big.NewInt(0).Set(value), - RcvAddr: rcvAddr, - SndAddr: player.Address, - GasPrice: integrationTests.MinTxGasPrice, - GasLimit: gasLimit, - Data: txData, - ChainID: integrationTests.ChainID, - Version: integrationTests.MinTransactionVersion, - RelayerAddr: relayerAddress, + Nonce: player.Nonce, + Value: big.NewInt(0).Set(value), + RcvAddr: rcvAddr, + SndAddr: player.Address, + GasPrice: integrationTests.MinTxGasPrice, + GasLimit: gasLimit, + Data: txData, + ChainID: integrationTests.ChainID, + Version: integrationTests.MinTransactionVersion, } txBuff, _ := tx.GetDataForSigning(integrationTests.TestAddressPubkeyConverter, integrationTests.TestTxSignMarshalizer, integrationTests.TestTxSignHasher) tx.Signature, _ = player.SingleSigner.Sign(player.SkTxSign, txBuff) @@ -238,37 +212,6 @@ func createRelayedTxV2( return tx } -func createRelayedTxV3( - economicsFee process.FeeHandler, - relayer *integrationTests.TestWalletAccount, - userTx *transaction.Transaction, -) *transaction.Transaction { - tx := &transaction.Transaction{ - Nonce: relayer.Nonce, - Value: big.NewInt(0), - RcvAddr: relayer.Address, - SndAddr: relayer.Address, - GasPrice: integrationTests.MinTxGasPrice, - Data: []byte(""), - ChainID: userTx.ChainID, - Version: userTx.Version, - InnerTransactions: []*transaction.Transaction{userTx}, - } - gasLimit := economicsFee.ComputeGasLimit(tx) - tx.GasLimit = userTx.GasLimit + gasLimit - - txBuff, _ := tx.GetDataForSigning(integrationTests.TestAddressPubkeyConverter, integrationTests.TestTxSignMarshalizer, integrationTests.TestTxSignHasher) - tx.Signature, _ = relayer.SingleSigner.Sign(relayer.SkTxSign, txBuff) - relayer.Nonce++ - - relayer.Balance.Sub(relayer.Balance, tx.Value) - - txFee := economicsFee.ComputeTxFee(tx) - relayer.Balance.Sub(relayer.Balance, txFee) - - return tx -} - func createAndSendSimpleTransaction( nodes []*integrationTests.TestProcessorNode, player *integrationTests.TestWalletAccount, @@ -279,7 +222,7 @@ func createAndSendSimpleTransaction( ) { txDispatcherNode := getNodeWithinSameShardAsPlayer(nodes, player.Address) - userTx := createUserTx(player, rcvAddr, value, gasLimit, txData, nil) + userTx := createUserTx(player, rcvAddr, value, gasLimit, txData) _, err := txDispatcherNode.SendTransaction(userTx) if err != nil { fmt.Println(err.Error()) diff --git a/integrationTests/multiShard/relayedTx/relayedTx_test.go b/integrationTests/multiShard/relayedTx/relayedTx_test.go index d9ea772d7ba..87a54633953 100644 --- a/integrationTests/multiShard/relayedTx/relayedTx_test.go +++ b/integrationTests/multiShard/relayedTx/relayedTx_test.go @@ -33,24 +33,20 @@ type createAndSendRelayedAndUserTxFuncType = func( func TestRelayedTransactionInMultiShardEnvironmentWithNormalTx(t *testing.T) { t.Run("relayed v1", testRelayedTransactionInMultiShardEnvironmentWithNormalTx(CreateAndSendRelayedAndUserTx, false)) - t.Run("relayed v3", testRelayedTransactionInMultiShardEnvironmentWithNormalTx(CreateAndSendRelayedAndUserTxV3, true)) } func TestRelayedTransactionInMultiShardEnvironmentWithSmartContractTX(t *testing.T) { t.Run("relayed v1", testRelayedTransactionInMultiShardEnvironmentWithSmartContractTX(CreateAndSendRelayedAndUserTx, false)) t.Run("relayed v2", testRelayedTransactionInMultiShardEnvironmentWithSmartContractTX(CreateAndSendRelayedAndUserTxV2, false)) - t.Run("relayed v3", testRelayedTransactionInMultiShardEnvironmentWithSmartContractTX(CreateAndSendRelayedAndUserTxV3, true)) } func TestRelayedTransactionInMultiShardEnvironmentWithESDTTX(t *testing.T) { t.Run("relayed v1", testRelayedTransactionInMultiShardEnvironmentWithESDTTX(CreateAndSendRelayedAndUserTx, false)) t.Run("relayed v2", testRelayedTransactionInMultiShardEnvironmentWithESDTTX(CreateAndSendRelayedAndUserTxV2, false)) - t.Run("relayed v3", testRelayedTransactionInMultiShardEnvironmentWithESDTTX(CreateAndSendRelayedAndUserTxV3, true)) } func TestRelayedTransactionInMultiShardEnvironmentWithAttestationContract(t *testing.T) { t.Run("relayed v1", testRelayedTransactionInMultiShardEnvironmentWithAttestationContract(CreateAndSendRelayedAndUserTx, false)) - t.Run("relayed v3", testRelayedTransactionInMultiShardEnvironmentWithAttestationContract(CreateAndSendRelayedAndUserTxV3, true)) } func testRelayedTransactionInMultiShardEnvironmentWithNormalTx( diff --git a/integrationTests/testHeartbeatNode.go b/integrationTests/testHeartbeatNode.go index 43b2ac576a0..1ba488b9e12 100644 --- a/integrationTests/testHeartbeatNode.go +++ b/integrationTests/testHeartbeatNode.go @@ -54,7 +54,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/genesisMocks" "github.com/multiversx/mx-chain-go/testscommon/nodeTypeProviderMock" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" trieMock "github.com/multiversx/mx-chain-go/testscommon/trie" vic "github.com/multiversx/mx-chain-go/testscommon/validatorInfoCacher" @@ -627,7 +626,6 @@ func (thn *TestHeartbeatNode) initInterceptors() { SignaturesHandler: &processMock.SignaturesHandlerStub{}, HeartbeatExpiryTimespanInSec: thn.heartbeatExpiryTimespanInSec, PeerID: thn.MainMessenger.ID(), - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, } thn.createPeerAuthInterceptor(argsFactory) diff --git a/integrationTests/testInitializer.go b/integrationTests/testInitializer.go index 06dc1a24866..a7c6cdac3c3 100644 --- a/integrationTests/testInitializer.go +++ b/integrationTests/testInitializer.go @@ -69,7 +69,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/guardianMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/stakingcommon" testStorage "github.com/multiversx/mx-chain-go/testscommon/state" statusHandlerMock "github.com/multiversx/mx-chain-go/testscommon/statusHandler" @@ -1056,17 +1055,15 @@ func CreateSimpleTxProcessor(accnts state.AccountsAdapter) process.TransactionPr return fee }, }, - ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, - BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, - EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, - EnableEpochsHandler: &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - TxVersionChecker: &testscommon.TxVersionCheckerStub{}, - GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, - TxLogsProcessor: &mock.TxLogsProcessorStub{}, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, + BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, + EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, + EnableEpochsHandler: &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, + TxVersionChecker: &testscommon.TxVersionCheckerStub{}, + GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, + TxLogsProcessor: &mock.TxLogsProcessorStub{}, } txProcessor, _ := txProc.NewTxProcessor(argsNewTxProcessor) diff --git a/integrationTests/testProcessorNode.go b/integrationTests/testProcessorNode.go index cf76e1582d0..dc828291384 100644 --- a/integrationTests/testProcessorNode.go +++ b/integrationTests/testProcessorNode.go @@ -114,7 +114,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/mainFactoryMocks" "github.com/multiversx/mx-chain-go/testscommon/outport" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" "github.com/multiversx/mx-chain-go/testscommon/stakingcommon" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" @@ -1288,12 +1287,6 @@ func (tpn *TestProcessorNode) initInterceptors(heartbeatPk string) { cryptoComponents.BlKeyGen = tpn.OwnAccount.KeygenBlockSign cryptoComponents.TxKeyGen = tpn.OwnAccount.KeygenTxSign - relayedV3TxProcessor, _ := transaction.NewRelayedTxV3Processor(transaction.ArgRelayedTxV3Processor{ - EconomicsFee: tpn.EconomicsData, - ShardCoordinator: tpn.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - if tpn.ShardCoordinator.SelfId() == core.MetachainShardId { argsEpochStart := &metachain.ArgsNewMetaEpochStartTrigger{ GenesisTime: tpn.RoundHandler.TimeStamp(), @@ -1346,7 +1339,6 @@ func (tpn *TestProcessorNode) initInterceptors(heartbeatPk string) { FullArchivePeerShardMapper: tpn.FullArchivePeerShardMapper, HardforkTrigger: tpn.HardforkTrigger, NodeOperationMode: tpn.NodeOperationMode, - RelayedTxV3Processor: relayedV3TxProcessor, } interceptorContainerFactory, _ := interceptorscontainer.NewMetaInterceptorsContainerFactory(metaInterceptorContainerFactoryArgs) @@ -1415,7 +1407,6 @@ func (tpn *TestProcessorNode) initInterceptors(heartbeatPk string) { FullArchivePeerShardMapper: tpn.FullArchivePeerShardMapper, HardforkTrigger: tpn.HardforkTrigger, NodeOperationMode: tpn.NodeOperationMode, - RelayedTxV3Processor: relayedV3TxProcessor, } interceptorContainerFactory, _ := interceptorscontainer.NewShardInterceptorsContainerFactory(shardIntereptorContainerFactoryArgs) @@ -1696,66 +1687,56 @@ func (tpn *TestProcessorNode) initInnerProcessors(gasMap map[string]map[string]u EnableEpochsHandler: tpn.EnableEpochsHandler, } txTypeHandler, _ := coordinator.NewTxTypeHandler(argsTxTypeHandler) - _ = tpn.EconomicsData.SetTxTypeHandler(txTypeHandler) tpn.GasHandler, _ = preprocess.NewGasComputation(tpn.EconomicsData, txTypeHandler, tpn.EnableEpochsHandler) badBlocksHandler, _ := tpn.InterimProcContainer.Get(dataBlock.InvalidBlock) argsNewScProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: tpn.VMContainer, - ArgsParser: tpn.ArgsParser, - Hasher: TestHasher, - Marshalizer: TestMarshalizer, - AccountsDB: tpn.AccntState, - BlockChainHook: vmFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: TestAddressPubkeyConverter, - ShardCoordinator: tpn.ShardCoordinator, - ScrForwarder: tpn.ScrForwarder, - TxFeeHandler: tpn.FeeAccumulator, - EconomicsFee: tpn.EconomicsData, - TxTypeHandler: txTypeHandler, - GasHandler: tpn.GasHandler, - GasSchedule: gasSchedule, - TxLogsProcessor: tpn.TransactionLogProcessor, - BadTxForwarder: badBlocksHandler, - EnableRoundsHandler: tpn.EnableRoundsHandler, - EnableEpochsHandler: tpn.EnableEpochsHandler, - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: tpn.WasmVMChangeLocker, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + VmContainer: tpn.VMContainer, + ArgsParser: tpn.ArgsParser, + Hasher: TestHasher, + Marshalizer: TestMarshalizer, + AccountsDB: tpn.AccntState, + BlockChainHook: vmFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: TestAddressPubkeyConverter, + ShardCoordinator: tpn.ShardCoordinator, + ScrForwarder: tpn.ScrForwarder, + TxFeeHandler: tpn.FeeAccumulator, + EconomicsFee: tpn.EconomicsData, + TxTypeHandler: txTypeHandler, + GasHandler: tpn.GasHandler, + GasSchedule: gasSchedule, + TxLogsProcessor: tpn.TransactionLogProcessor, + BadTxForwarder: badBlocksHandler, + EnableRoundsHandler: tpn.EnableRoundsHandler, + EnableEpochsHandler: tpn.EnableEpochsHandler, + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: tpn.WasmVMChangeLocker, } tpn.ScProcessor, _ = processProxy.NewTestSmartContractProcessorProxy(argsNewScProcessor, tpn.EpochNotifier) - relayedV3TxProcessor, _ := transaction.NewRelayedTxV3Processor(transaction.ArgRelayedTxV3Processor{ - EconomicsFee: tpn.EconomicsData, - ShardCoordinator: tpn.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - receiptsHandler, _ := tpn.InterimProcContainer.Get(dataBlock.ReceiptBlock) argsNewTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: tpn.AccntState, - Hasher: TestHasher, - PubkeyConv: TestAddressPubkeyConverter, - Marshalizer: TestMarshalizer, - SignMarshalizer: TestTxSignMarshalizer, - ShardCoordinator: tpn.ShardCoordinator, - ScProcessor: tpn.ScProcessor, - TxFeeHandler: tpn.FeeAccumulator, - TxTypeHandler: txTypeHandler, - EconomicsFee: tpn.EconomicsData, - ReceiptForwarder: receiptsHandler, - BadTxForwarder: badBlocksHandler, - ArgsParser: tpn.ArgsParser, - ScrForwarder: tpn.ScrForwarder, - EnableRoundsHandler: tpn.EnableRoundsHandler, - EnableEpochsHandler: tpn.EnableEpochsHandler, - GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, - TxVersionChecker: &testscommon.TxVersionCheckerStub{}, - TxLogsProcessor: tpn.TransactionLogProcessor, - RelayedTxV3Processor: relayedV3TxProcessor, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + Accounts: tpn.AccntState, + Hasher: TestHasher, + PubkeyConv: TestAddressPubkeyConverter, + Marshalizer: TestMarshalizer, + SignMarshalizer: TestTxSignMarshalizer, + ShardCoordinator: tpn.ShardCoordinator, + ScProcessor: tpn.ScProcessor, + TxFeeHandler: tpn.FeeAccumulator, + TxTypeHandler: txTypeHandler, + EconomicsFee: tpn.EconomicsData, + ReceiptForwarder: receiptsHandler, + BadTxForwarder: badBlocksHandler, + ArgsParser: tpn.ArgsParser, + ScrForwarder: tpn.ScrForwarder, + EnableRoundsHandler: tpn.EnableRoundsHandler, + EnableEpochsHandler: tpn.EnableEpochsHandler, + GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, + TxVersionChecker: &testscommon.TxVersionCheckerStub{}, + TxLogsProcessor: tpn.TransactionLogProcessor, } tpn.TxProcessor, _ = transaction.NewTxProcessor(argsNewTxProcessor) scheduledSCRsStorer, _ := tpn.Storage.GetStorer(dataRetriever.ScheduledSCRsUnit) @@ -1986,32 +1967,30 @@ func (tpn *TestProcessorNode) initMetaInnerProcessors(gasMap map[string]map[stri EnableEpochsHandler: tpn.EnableEpochsHandler, } txTypeHandler, _ := coordinator.NewTxTypeHandler(argsTxTypeHandler) - _ = tpn.EconomicsData.SetTxTypeHandler(txTypeHandler) tpn.GasHandler, _ = preprocess.NewGasComputation(tpn.EconomicsData, txTypeHandler, tpn.EnableEpochsHandler) badBlocksHandler, _ := tpn.InterimProcContainer.Get(dataBlock.InvalidBlock) argsNewScProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: tpn.VMContainer, - ArgsParser: tpn.ArgsParser, - Hasher: TestHasher, - Marshalizer: TestMarshalizer, - AccountsDB: tpn.AccntState, - BlockChainHook: vmFactory.BlockChainHookImpl(), - BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), - PubkeyConv: TestAddressPubkeyConverter, - ShardCoordinator: tpn.ShardCoordinator, - ScrForwarder: tpn.ScrForwarder, - TxFeeHandler: tpn.FeeAccumulator, - EconomicsFee: tpn.EconomicsData, - TxTypeHandler: txTypeHandler, - GasHandler: tpn.GasHandler, - GasSchedule: gasSchedule, - TxLogsProcessor: tpn.TransactionLogProcessor, - BadTxForwarder: badBlocksHandler, - EnableRoundsHandler: tpn.EnableRoundsHandler, - EnableEpochsHandler: tpn.EnableEpochsHandler, - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: tpn.WasmVMChangeLocker, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + VmContainer: tpn.VMContainer, + ArgsParser: tpn.ArgsParser, + Hasher: TestHasher, + Marshalizer: TestMarshalizer, + AccountsDB: tpn.AccntState, + BlockChainHook: vmFactory.BlockChainHookImpl(), + BuiltInFunctions: builtInFuncFactory.BuiltInFunctionContainer(), + PubkeyConv: TestAddressPubkeyConverter, + ShardCoordinator: tpn.ShardCoordinator, + ScrForwarder: tpn.ScrForwarder, + TxFeeHandler: tpn.FeeAccumulator, + EconomicsFee: tpn.EconomicsData, + TxTypeHandler: txTypeHandler, + GasHandler: tpn.GasHandler, + GasSchedule: gasSchedule, + TxLogsProcessor: tpn.TransactionLogProcessor, + BadTxForwarder: badBlocksHandler, + EnableRoundsHandler: tpn.EnableRoundsHandler, + EnableEpochsHandler: tpn.EnableEpochsHandler, + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: tpn.WasmVMChangeLocker, } tpn.ScProcessor, _ = processProxy.NewTestSmartContractProcessorProxy(argsNewScProcessor, tpn.EpochNotifier) @@ -2614,22 +2593,21 @@ func (tpn *TestProcessorNode) SendTransaction(tx *dataTransaction.Transaction) ( guardianAddress = TestAddressPubkeyConverter.SilentEncode(tx.GuardianAddr, log) } createTxArgs := &external.ArgsCreateTransaction{ - Nonce: tx.Nonce, - Value: tx.Value.String(), - Receiver: encodedRcvAddr, - ReceiverUsername: nil, - Sender: encodedSndAddr, - SenderUsername: nil, - GasPrice: tx.GasPrice, - GasLimit: tx.GasLimit, - DataField: tx.Data, - SignatureHex: hex.EncodeToString(tx.Signature), - ChainID: string(tx.ChainID), - Version: tx.Version, - Options: tx.Options, - Guardian: guardianAddress, - GuardianSigHex: hex.EncodeToString(tx.GuardianSignature), - InnerTransactions: tx.InnerTransactions, + Nonce: tx.Nonce, + Value: tx.Value.String(), + Receiver: encodedRcvAddr, + ReceiverUsername: nil, + Sender: encodedSndAddr, + SenderUsername: nil, + GasPrice: tx.GasPrice, + GasLimit: tx.GasLimit, + DataField: tx.Data, + SignatureHex: hex.EncodeToString(tx.Signature), + ChainID: string(tx.ChainID), + Version: tx.Version, + Options: tx.Options, + Guardian: guardianAddress, + GuardianSigHex: hex.EncodeToString(tx.GuardianSignature), } tx, txHash, err := tpn.Node.CreateTransaction(createTxArgs) if err != nil { @@ -3275,7 +3253,6 @@ func CreateEnableEpochsConfig() config.EnableEpochs { MiniBlockPartialExecutionEnableEpoch: UnreachableEpoch, RefactorPeersMiniBlocksEnableEpoch: UnreachableEpoch, SCProcessorV2EnableEpoch: UnreachableEpoch, - RelayedTransactionsV3EnableEpoch: UnreachableEpoch, FixRelayedBaseCostEnableEpoch: UnreachableEpoch, FixRelayedMoveBalanceToNonPayableSCEnableEpoch: UnreachableEpoch, } @@ -3363,11 +3340,6 @@ func GetDefaultProcessComponents() *mock.ProcessComponentsStub { CurrentEpochProviderInternal: &testscommon.CurrentEpochProviderStub{}, HistoryRepositoryInternal: &dblookupextMock.HistoryRepositoryStub{}, HardforkTriggerField: &testscommon.HardforkTriggerStub{}, - RelayedTxV3ProcessorField: &processMocks.RelayedTxV3ProcessorMock{ - CheckRelayedTxCalled: func(tx *dataTransaction.Transaction) error { - return nil - }, - }, } } diff --git a/integrationTests/testProcessorNodeWithTestWebServer.go b/integrationTests/testProcessorNodeWithTestWebServer.go index d533f4c75b1..b4e2490b900 100644 --- a/integrationTests/testProcessorNodeWithTestWebServer.go +++ b/integrationTests/testProcessorNodeWithTestWebServer.go @@ -163,7 +163,6 @@ func createFacadeComponents(tpn *TestProcessorNode) nodeFacade.ApiResolver { } txTypeHandler, err := coordinator.NewTxTypeHandler(argsTxTypeHandler) log.LogIfError(err) - _ = tpn.EconomicsData.SetTxTypeHandler(txTypeHandler) argsDataFieldParser := &datafield.ArgsOperationDataFieldParser{ AddressLength: TestAddressPubkeyConverter.Len(), diff --git a/integrationTests/vm/testInitializer.go b/integrationTests/vm/testInitializer.go index c701007ca00..c6e33ddc21a 100644 --- a/integrationTests/vm/testInitializer.go +++ b/integrationTests/vm/testInitializer.go @@ -62,7 +62,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/genesisMocks" "github.com/multiversx/mx-chain-go/testscommon/integrationtests" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" storageStubs "github.com/multiversx/mx-chain-go/testscommon/storage" "github.com/multiversx/mx-chain-go/testscommon/txDataBuilder" @@ -141,9 +140,8 @@ type VMTestContext struct { ContractOwner VMTestAccount Contract VMTestAccount - TxCostHandler external.TransactionEvaluator - TxsLogsProcessor process.TransactionLogProcessor - FailedTxLogsAccumulator process.FailedTxLogsAccumulator + TxCostHandler external.TransactionEvaluator + TxsLogsProcessor process.TransactionLogProcessor } // Close - @@ -443,7 +441,6 @@ func CreateTxProcessorWithOneSCExecutorMockVM( if err != nil { return nil, err } - _ = economicsData.SetTxTypeHandler(txTypeHandler) argsNewSCProcessor := scrCommon.ArgsNewSmartContractProcessor{ VmContainer: vmContainer, @@ -463,13 +460,12 @@ func CreateTxProcessorWithOneSCExecutorMockVM( GasHandler: &testscommon.GasHandlerStub{ SetGasRefundedCalled: func(gasRefunded uint64, hash []byte) {}, }, - GasSchedule: gasScheduleNotifier, - TxLogsProcessor: &mock.TxLogsProcessorStub{}, - EnableEpochsHandler: enableEpochsHandler, - EnableRoundsHandler: enableRoundsHandler, - VMOutputCacher: txcache.NewDisabledCache(), - WasmVMChangeLocker: wasmVMChangeLocker, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + GasSchedule: gasScheduleNotifier, + TxLogsProcessor: &mock.TxLogsProcessorStub{}, + EnableEpochsHandler: enableEpochsHandler, + EnableRoundsHandler: enableRoundsHandler, + VMOutputCacher: txcache.NewDisabledCache(), + WasmVMChangeLocker: wasmVMChangeLocker, } scProcessor, _ := processProxy.NewTestSmartContractProcessorProxy(argsNewSCProcessor, genericEpochNotifier) @@ -480,27 +476,25 @@ func CreateTxProcessorWithOneSCExecutorMockVM( } argsNewTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: accnts, - Hasher: integrationtests.TestHasher, - PubkeyConv: pubkeyConv, - Marshalizer: integrationtests.TestMarshalizer, - SignMarshalizer: integrationtests.TestMarshalizer, - ShardCoordinator: mock.NewMultiShardsCoordinatorMock(2), - ScProcessor: scProcessor, - TxFeeHandler: &testscommon.UnsignedTxHandlerStub{}, - TxTypeHandler: txTypeHandler, - EconomicsFee: economicsData, - ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, - BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - TxVersionChecker: versioning.NewTxVersionChecker(minTransactionVersion), - GuardianChecker: guardedAccountHandler, - TxLogsProcessor: &mock.TxLogsProcessorStub{}, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + Accounts: accnts, + Hasher: integrationtests.TestHasher, + PubkeyConv: pubkeyConv, + Marshalizer: integrationtests.TestMarshalizer, + SignMarshalizer: integrationtests.TestMarshalizer, + ShardCoordinator: mock.NewMultiShardsCoordinatorMock(2), + ScProcessor: scProcessor, + TxFeeHandler: &testscommon.UnsignedTxHandlerStub{}, + TxTypeHandler: txTypeHandler, + EconomicsFee: economicsData, + ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, + BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + TxVersionChecker: versioning.NewTxVersionChecker(minTransactionVersion), + GuardianChecker: guardedAccountHandler, + TxLogsProcessor: &mock.TxLogsProcessorStub{}, } return transaction.NewTxProcessor(argsNewTxProcessor) @@ -810,13 +804,12 @@ func CreateVMConfigWithVersion(version string) *config.VirtualMachineConfig { // ResultsCreateTxProcessor is the struct that will hold all needed processor instances type ResultsCreateTxProcessor struct { - TxProc process.TransactionProcessor - SCProc scrCommon.TestSmartContractProcessor - IntermediateTxProc process.IntermediateTransactionHandler - EconomicsHandler process.EconomicsDataHandler - CostHandler external.TransactionEvaluator - TxLogProc process.TransactionLogProcessor - FailedTxLogsAccumulator process.FailedTxLogsAccumulator + TxProc process.TransactionProcessor + SCProc scrCommon.TestSmartContractProcessor + IntermediateTxProc process.IntermediateTransactionHandler + EconomicsHandler process.EconomicsDataHandler + CostHandler external.TransactionEvaluator + TxLogProc process.TransactionLogProcessor } // CreateTxProcessorWithOneSCExecutorWithVMs - @@ -861,7 +854,6 @@ func CreateTxProcessorWithOneSCExecutorWithVMs( if err != nil { return nil, err } - _ = economicsData.SetTxTypeHandler(txTypeHandler) gasComp, err := preprocess.NewGasComputation(economicsData, txTypeHandler, enableEpochsHandler) if err != nil { @@ -873,58 +865,53 @@ func CreateTxProcessorWithOneSCExecutorWithVMs( Marshalizer: integrationtests.TestMarshalizer, }) - failedLogsAcc := transactionLog.NewFailedTxLogsAccumulator() - intermediateTxHandler := &mock.IntermediateTransactionHandlerMock{} argsNewSCProcessor := scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: vmContainer, - ArgsParser: smartContract.NewArgumentParser(), - Hasher: integrationtests.TestHasher, - Marshalizer: integrationtests.TestMarshalizer, - AccountsDB: accnts, - BlockChainHook: blockChainHook, - BuiltInFunctions: blockChainHook.GetBuiltinFunctionsContainer(), - PubkeyConv: pubkeyConv, - ShardCoordinator: shardCoordinator, - ScrForwarder: intermediateTxHandler, - BadTxForwarder: intermediateTxHandler, - TxFeeHandler: feeAccumulator, - EconomicsFee: economicsData, - TxTypeHandler: txTypeHandler, - GasHandler: gasComp, - GasSchedule: mock.NewGasScheduleNotifierMock(gasSchedule), - TxLogsProcessor: logProc, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - WasmVMChangeLocker: wasmVMChangeLocker, - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + VmContainer: vmContainer, + ArgsParser: smartContract.NewArgumentParser(), + Hasher: integrationtests.TestHasher, + Marshalizer: integrationtests.TestMarshalizer, + AccountsDB: accnts, + BlockChainHook: blockChainHook, + BuiltInFunctions: blockChainHook.GetBuiltinFunctionsContainer(), + PubkeyConv: pubkeyConv, + ShardCoordinator: shardCoordinator, + ScrForwarder: intermediateTxHandler, + BadTxForwarder: intermediateTxHandler, + TxFeeHandler: feeAccumulator, + EconomicsFee: economicsData, + TxTypeHandler: txTypeHandler, + GasHandler: gasComp, + GasSchedule: mock.NewGasScheduleNotifierMock(gasSchedule), + TxLogsProcessor: logProc, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + WasmVMChangeLocker: wasmVMChangeLocker, + VMOutputCacher: txcache.NewDisabledCache(), } scProcessorProxy, _ := processProxy.NewTestSmartContractProcessorProxy(argsNewSCProcessor, epochNotifierInstance) argsNewTxProcessor := transaction.ArgsNewTxProcessor{ - Accounts: accnts, - Hasher: integrationtests.TestHasher, - PubkeyConv: pubkeyConv, - Marshalizer: integrationtests.TestMarshalizer, - SignMarshalizer: integrationtests.TestMarshalizer, - ShardCoordinator: shardCoordinator, - ScProcessor: scProcessorProxy, - TxFeeHandler: feeAccumulator, - TxTypeHandler: txTypeHandler, - EconomicsFee: economicsData, - ReceiptForwarder: intermediateTxHandler, - BadTxForwarder: intermediateTxHandler, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: intermediateTxHandler, - EnableRoundsHandler: enableRoundsHandler, - EnableEpochsHandler: enableEpochsHandler, - TxVersionChecker: versioning.NewTxVersionChecker(minTransactionVersion), - GuardianChecker: guardianChecker, - TxLogsProcessor: logProc, - FailedTxLogsAccumulator: failedLogsAcc, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, + Accounts: accnts, + Hasher: integrationtests.TestHasher, + PubkeyConv: pubkeyConv, + Marshalizer: integrationtests.TestMarshalizer, + SignMarshalizer: integrationtests.TestMarshalizer, + ShardCoordinator: shardCoordinator, + ScProcessor: scProcessorProxy, + TxFeeHandler: feeAccumulator, + TxTypeHandler: txTypeHandler, + EconomicsFee: economicsData, + ReceiptForwarder: intermediateTxHandler, + BadTxForwarder: intermediateTxHandler, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: intermediateTxHandler, + EnableRoundsHandler: enableRoundsHandler, + EnableEpochsHandler: enableEpochsHandler, + TxVersionChecker: versioning.NewTxVersionChecker(minTransactionVersion), + GuardianChecker: guardianChecker, + TxLogsProcessor: logProc, } txProcessor, err := transaction.NewTxProcessor(argsNewTxProcessor) if err != nil { @@ -1331,24 +1318,23 @@ func CreatePreparedTxProcessorWithVMConfigWithShardCoordinatorDBAndGasAndRoundCo } return &VMTestContext{ - TxProcessor: res.TxProc, - ScProcessor: res.SCProc, - Accounts: accounts, - BlockchainHook: blockchainHook, - VMContainer: vmContainer, - TxFeeHandler: feeAccumulator, - ScForwarder: res.IntermediateTxProc, - ShardCoordinator: shardCoordinator, - EconomicsData: res.EconomicsHandler, - TxCostHandler: res.CostHandler, - TxsLogsProcessor: res.TxLogProc, - FailedTxLogsAccumulator: res.FailedTxLogsAccumulator, - GasSchedule: gasScheduleNotifier, - EpochNotifier: epochNotifierInstance, - EnableEpochsHandler: enableEpochsHandler, - ChainHandler: chainHandler, - Marshalizer: integrationtests.TestMarshalizer, - GuardedAccountsHandler: guardedAccountHandler, + TxProcessor: res.TxProc, + ScProcessor: res.SCProc, + Accounts: accounts, + BlockchainHook: blockchainHook, + VMContainer: vmContainer, + TxFeeHandler: feeAccumulator, + ScForwarder: res.IntermediateTxProc, + ShardCoordinator: shardCoordinator, + EconomicsData: res.EconomicsHandler, + TxCostHandler: res.CostHandler, + TxsLogsProcessor: res.TxLogProc, + GasSchedule: gasScheduleNotifier, + EpochNotifier: epochNotifierInstance, + EnableEpochsHandler: enableEpochsHandler, + ChainHandler: chainHandler, + Marshalizer: integrationtests.TestMarshalizer, + GuardedAccountsHandler: guardedAccountHandler, }, nil } @@ -1945,22 +1931,21 @@ func CreatePreparedTxProcessorWithVMsMultiShardRoundVMConfig( } return &VMTestContext{ - TxProcessor: res.TxProc, - ScProcessor: res.SCProc, - Accounts: accounts, - BlockchainHook: blockchainHook, - VMContainer: vmContainer, - TxFeeHandler: feeAccumulator, - ShardCoordinator: shardCoordinator, - ScForwarder: res.IntermediateTxProc, - EconomicsData: res.EconomicsHandler, - Marshalizer: integrationtests.TestMarshalizer, - TxsLogsProcessor: res.TxLogProc, - FailedTxLogsAccumulator: res.FailedTxLogsAccumulator, - EpochNotifier: epochNotifierInstance, - EnableEpochsHandler: enableEpochsHandler, - ChainHandler: chainHandler, - GuardedAccountsHandler: guardedAccountHandler, + TxProcessor: res.TxProc, + ScProcessor: res.SCProc, + Accounts: accounts, + BlockchainHook: blockchainHook, + VMContainer: vmContainer, + TxFeeHandler: feeAccumulator, + ShardCoordinator: shardCoordinator, + ScForwarder: res.IntermediateTxProc, + EconomicsData: res.EconomicsHandler, + Marshalizer: integrationtests.TestMarshalizer, + TxsLogsProcessor: res.TxLogProc, + EpochNotifier: epochNotifierInstance, + EnableEpochsHandler: enableEpochsHandler, + ChainHandler: chainHandler, + GuardedAccountsHandler: guardedAccountHandler, }, nil } diff --git a/integrationTests/vm/wasm/utils.go b/integrationTests/vm/wasm/utils.go index 7ec28bb8f45..bfe7b4b7ca9 100644 --- a/integrationTests/vm/wasm/utils.go +++ b/integrationTests/vm/wasm/utils.go @@ -53,7 +53,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/guardianMocks" "github.com/multiversx/mx-chain-go/testscommon/integrationtests" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" storageStubs "github.com/multiversx/mx-chain-go/testscommon/storage" "github.com/multiversx/mx-chain-go/vm/systemSmartContracts/defaults" vmcommon "github.com/multiversx/mx-chain-vm-common-go" @@ -392,40 +391,37 @@ func (context *TestContext) initTxProcessorWithOneSCExecutorWithVMs() { GasHandler: &testscommon.GasHandlerStub{ SetGasRefundedCalled: func(gasRefunded uint64, hash []byte) {}, }, - GasSchedule: mock.NewGasScheduleNotifierMock(gasSchedule), - TxLogsProcessor: context.TxLogsProcessor, - EnableRoundsHandler: context.EnableRoundsHandler, - EnableEpochsHandler: context.EnableEpochsHandler, - WasmVMChangeLocker: context.WasmVMChangeLocker, - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + GasSchedule: mock.NewGasScheduleNotifierMock(gasSchedule), + TxLogsProcessor: context.TxLogsProcessor, + EnableRoundsHandler: context.EnableRoundsHandler, + EnableEpochsHandler: context.EnableEpochsHandler, + WasmVMChangeLocker: context.WasmVMChangeLocker, + VMOutputCacher: txcache.NewDisabledCache(), } context.ScProcessor, err = processProxy.NewTestSmartContractProcessorProxy(argsNewSCProcessor, context.EpochNotifier) require.Nil(context.T, err) argsNewTxProcessor := processTransaction.ArgsNewTxProcessor{ - Accounts: context.Accounts, - Hasher: hasher, - PubkeyConv: pkConverter, - Marshalizer: marshalizer, - SignMarshalizer: marshalizer, - ShardCoordinator: oneShardCoordinator, - ScProcessor: context.ScProcessor, - TxFeeHandler: context.UnsignexTxHandler, - TxTypeHandler: txTypeHandler, - EconomicsFee: context.EconomicsFee, - ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, - BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, - EnableRoundsHandler: context.EnableRoundsHandler, - EnableEpochsHandler: context.EnableEpochsHandler, - TxVersionChecker: &testscommon.TxVersionCheckerStub{}, - GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, - TxLogsProcessor: context.TxLogsProcessor, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + Accounts: context.Accounts, + Hasher: hasher, + PubkeyConv: pkConverter, + Marshalizer: marshalizer, + SignMarshalizer: marshalizer, + ShardCoordinator: oneShardCoordinator, + ScProcessor: context.ScProcessor, + TxFeeHandler: context.UnsignexTxHandler, + TxTypeHandler: txTypeHandler, + EconomicsFee: context.EconomicsFee, + ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, + BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, + EnableRoundsHandler: context.EnableRoundsHandler, + EnableEpochsHandler: context.EnableEpochsHandler, + TxVersionChecker: &testscommon.TxVersionCheckerStub{}, + GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, + TxLogsProcessor: context.TxLogsProcessor, } context.TxProcessor, err = processTransaction.NewTxProcessor(argsNewTxProcessor) diff --git a/integrationTests/vm/wasm/wasmvm/wasmVM_test.go b/integrationTests/vm/wasm/wasmvm/wasmVM_test.go index 9ad6a861235..2957aa42add 100644 --- a/integrationTests/vm/wasm/wasmvm/wasmVM_test.go +++ b/integrationTests/vm/wasm/wasmvm/wasmVM_test.go @@ -31,7 +31,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/economicsmocks" "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/integrationtests" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" logger "github.com/multiversx/mx-chain-logger-go" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/multiversx/mx-chain-vm-common-go/builtInFunctions" @@ -630,25 +629,23 @@ func TestExecuteTransactionAndTimeToProcessChange(t *testing.T) { _, _ = vm.CreateAccount(accnts, ownerAddressBytes, ownerNonce, ownerBalance) argsNewTxProcessor := processTransaction.ArgsNewTxProcessor{ - Accounts: accnts, - Hasher: testHasher, - PubkeyConv: pubkeyConv, - Marshalizer: testMarshalizer, - SignMarshalizer: testMarshalizer, - ShardCoordinator: shardCoordinator, - ScProcessor: &testscommon.SCProcessorMock{}, - TxFeeHandler: &testscommon.UnsignedTxHandlerStub{}, - TxTypeHandler: txTypeHandler, - EconomicsFee: &economicsmocks.EconomicsHandlerStub{}, - ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, - BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, - ArgsParser: smartContract.NewArgumentParser(), - ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, - EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, - EnableEpochsHandler: &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - TxLogsProcessor: &mock.TxLogsProcessorStub{}, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + Accounts: accnts, + Hasher: testHasher, + PubkeyConv: pubkeyConv, + Marshalizer: testMarshalizer, + SignMarshalizer: testMarshalizer, + ShardCoordinator: shardCoordinator, + ScProcessor: &testscommon.SCProcessorMock{}, + TxFeeHandler: &testscommon.UnsignedTxHandlerStub{}, + TxTypeHandler: txTypeHandler, + EconomicsFee: &economicsmocks.EconomicsHandlerStub{}, + ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, + BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, + ArgsParser: smartContract.NewArgumentParser(), + ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, + EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, + EnableEpochsHandler: &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, + TxLogsProcessor: &mock.TxLogsProcessorStub{}, } txProc, _ := processTransaction.NewTxProcessor(argsNewTxProcessor) diff --git a/node/chainSimulator/components/processComponents.go b/node/chainSimulator/components/processComponents.go index 6e00d776784..cbd119fa517 100644 --- a/node/chainSimulator/components/processComponents.go +++ b/node/chainSimulator/components/processComponents.go @@ -100,7 +100,6 @@ type processComponentsHolder struct { accountsParser genesis.AccountsParser sentSignatureTracker process.SentSignaturesTracker epochStartSystemSCProcessor process.EpochStartSystemSCProcessor - relayedTxV3Processor process.RelayedTxV3Processor managedProcessComponentsCloser io.Closer } @@ -284,7 +283,6 @@ func CreateProcessComponents(args ArgsProcessComponentsHolder) (*processComponen accountsParser: managedProcessComponents.AccountsParser(), sentSignatureTracker: managedProcessComponents.SentSignaturesTracker(), epochStartSystemSCProcessor: managedProcessComponents.EpochSystemSCProcessor(), - relayedTxV3Processor: managedProcessComponents.RelayedTxV3Processor(), managedProcessComponentsCloser: managedProcessComponents, } @@ -525,11 +523,6 @@ func (p *processComponentsHolder) EpochSystemSCProcessor() process.EpochStartSys return p.epochStartSystemSCProcessor } -// RelayedTxV3Processor returns the relayed tx v3 processor -func (p *processComponentsHolder) RelayedTxV3Processor() process.RelayedTxV3Processor { - return p.relayedTxV3Processor -} - // Close will call the Close methods on all inner components func (p *processComponentsHolder) Close() error { return p.managedProcessComponentsCloser.Close() diff --git a/node/chainSimulator/components/processComponents_test.go b/node/chainSimulator/components/processComponents_test.go index 93b6a7689a3..a8cb2f053e7 100644 --- a/node/chainSimulator/components/processComponents_test.go +++ b/node/chainSimulator/components/processComponents_test.go @@ -408,7 +408,6 @@ func TestProcessComponentsHolder_Getters(t *testing.T) { require.NotNil(t, comp.AccountsParser()) require.NotNil(t, comp.ReceiptsRepository()) require.NotNil(t, comp.EpochSystemSCProcessor()) - require.NotNil(t, comp.RelayedTxV3Processor()) require.Nil(t, comp.CheckSubcomponents()) require.Empty(t, comp.String()) diff --git a/node/external/dtos.go b/node/external/dtos.go index 12a6b153c46..ad8d073967b 100644 --- a/node/external/dtos.go +++ b/node/external/dtos.go @@ -1,24 +1,21 @@ package external -import "github.com/multiversx/mx-chain-core-go/data/transaction" - // ArgsCreateTransaction defines arguments for creating a transaction type ArgsCreateTransaction struct { - Nonce uint64 - Value string - Receiver string - ReceiverUsername []byte - Sender string - SenderUsername []byte - GasPrice uint64 - GasLimit uint64 - DataField []byte - SignatureHex string - ChainID string - Version uint32 - Options uint32 - Guardian string - GuardianSigHex string - Relayer string - InnerTransactions []*transaction.Transaction + Nonce uint64 + Value string + Receiver string + ReceiverUsername []byte + Sender string + SenderUsername []byte + GasPrice uint64 + GasLimit uint64 + DataField []byte + SignatureHex string + ChainID string + Version uint32 + Options uint32 + Guardian string + GuardianSigHex string + Relayer string } diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor.go b/node/external/transactionAPI/gasUsedAndFeeProcessor.go index 530b6b81b3d..ab5c77fee40 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor.go @@ -58,24 +58,17 @@ func (gfp *gasUsedAndFeeProcessor) computeAndAttachGasUsedAndFee(tx *transaction } hasRefundForSender := false - totalRefunds := big.NewInt(0) for _, scr := range tx.SmartContractResults { if !scr.IsRefund || scr.RcvAddr != tx.Sender { continue } + if scr.RcvAddr != tx.Sender { + continue + } + gfp.setGasUsedAndFeeBaseOnRefundValue(tx, scr.Value) hasRefundForSender = true - totalRefunds.Add(totalRefunds, scr.Value) - } - - if totalRefunds.Cmp(big.NewInt(0)) > 0 { - gasUsed, fee = gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, totalRefunds) - tx.GasUsed = gasUsed - tx.Fee = fee.String() - } - - if isRelayedAfterFix { - return + break } gfp.prepareTxWithResultsBasedOnLogs(tx, hasRefundForSender) @@ -86,10 +79,6 @@ func (gfp *gasUsedAndFeeProcessor) getFeeOfRelayed(tx *transaction.ApiTransactio return nil, false } - if len(tx.InnerTransactions) > 0 { - return gfp.feeComputer.ComputeTransactionFee(tx), true - } - if len(tx.Data) == 0 { return nil, false } @@ -180,6 +169,16 @@ func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnLogEvent(tx *transactio } } +func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnRefundValue(tx *transaction.ApiTransactionResult, refund *big.Int) { + + gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, refund) + + tx.GasUsed = gasUsed + + tx.Fee = fee.String() + +} + func (gfp *gasUsedAndFeeProcessor) isESDTOperationWithSCCall(tx *transaction.ApiTransactionResult) bool { isESDTTransferOperation := tx.Operation == core.BuiltInFunctionESDTTransfer || tx.Operation == core.BuiltInFunctionESDTNFTTransfer || tx.Operation == core.BuiltInFunctionMultiESDTNFTTransfer diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go index 7e4011e0f2c..c6abd9278d6 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go @@ -299,69 +299,6 @@ func TestComputeAndAttachGasUsedAndFeeTransactionWithMultipleScrWithRefund(t *te require.Equal(t, "319459080000000", txWithSRefundSCR.Fee) } -func TestComputeAndAttachGasUsedAndFeeRelayedV3WithRefund(t *testing.T) { - t.Parallel() - - feeComp, _ := fee.NewFeeComputer(createEconomicsData(&enableEpochsHandlerMock.EnableEpochsHandlerStub{ - IsFlagEnabledInEpochCalled: func(flag core.EnableEpochFlag, epoch uint32) bool { - return flag == common.GasPriceModifierFlag || - flag == common.PenalizedTooMuchGasFlag || - flag == common.FixRelayedBaseCostFlag - }, - })) - computer := fee.NewTestFeeComputer(feeComp) - - gasUsedAndFeeProc := newGasUsedAndFeeProcessor( - computer, - pubKeyConverter, - &testscommon.ArgumentParserMock{}, - &testscommon.MarshallerStub{}, - enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), - ) - - txWithSRefundSCR := &transaction.ApiTransactionResult{} - err := core.LoadJsonFile(txWithSRefundSCR, "testData/relayedV3WithOneRefund.json") - require.NoError(t, err) - - txWithSRefundSCR.Fee = "" - txWithSRefundSCR.GasUsed = 0 - - innerTxs := make([]*transaction.Transaction, 0, len(txWithSRefundSCR.InnerTransactions)) - for _, innerTx := range txWithSRefundSCR.InnerTransactions { - snd, _ := pubKeyConverter.Decode(innerTx.Sender) - rcv, _ := pubKeyConverter.Decode(innerTx.Receiver) - val, _ := big.NewInt(0).SetString(innerTx.Value, 10) - - innerTxs = append(innerTxs, &transaction.Transaction{ - Nonce: innerTx.Nonce, - Value: val, - RcvAddr: rcv, - SndAddr: snd, - GasPrice: innerTx.GasPrice, - GasLimit: innerTx.GasLimit, - Data: innerTx.Data, - }) - } - - snd, _ := pubKeyConverter.Decode(txWithSRefundSCR.Sender) - rcv, _ := pubKeyConverter.Decode(txWithSRefundSCR.Receiver) - val, _ := big.NewInt(0).SetString(txWithSRefundSCR.Value, 10) - txWithSRefundSCR.Tx = &transaction.Transaction{ - Nonce: txWithSRefundSCR.Nonce, - Value: val, - RcvAddr: rcv, - SndAddr: snd, - GasPrice: txWithSRefundSCR.GasPrice, - GasLimit: txWithSRefundSCR.GasLimit, - Data: txWithSRefundSCR.Data, - InnerTransactions: innerTxs, - } - - gasUsedAndFeeProc.computeAndAttachGasUsedAndFee(txWithSRefundSCR) - require.Equal(t, uint64(55149500), txWithSRefundSCR.GasUsed) - require.Equal(t, "699500000000000", txWithSRefundSCR.Fee) -} - func TestComputeAndAttachGasUsedAndFeeFailedRelayedV1(t *testing.T) { t.Parallel() @@ -405,7 +342,7 @@ func TestComputeAndAttachGasUsedAndFeeFailedRelayedV1(t *testing.T) { txWithSRefundSCR.GasUsed = 0 gasUsedAndFeeProc.computeAndAttachGasUsedAndFee(txWithSRefundSCR) - require.Equal(t, uint64(1274230), txWithSRefundSCR.GasUsed) - require.Equal(t, "1274230000000000", txWithSRefundSCR.Fee) + require.Equal(t, uint64(6148000), txWithSRefundSCR.GasUsed) + require.Equal(t, "1198000000000000", txWithSRefundSCR.Fee) require.Equal(t, "1274230000000000", txWithSRefundSCR.InitiallyPaidFee) } diff --git a/node/external/transactionAPI/testData/relayedV3WithOneRefund.json b/node/external/transactionAPI/testData/relayedV3WithOneRefund.json deleted file mode 100644 index c2b0484f877..00000000000 --- a/node/external/transactionAPI/testData/relayedV3WithOneRefund.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "type": "normal", - "processingTypeOnSource": "RelayedTxV3", - "processingTypeOnDestination": "RelayedTxV3", - "hash": "af1581562830e36b0bfb12c618a4ee92d6b7f2e0aa84935432a44c9b63cc8daa", - "nonce": 0, - "value": "0", - "receiver": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", - "sender": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", - "gasPrice": 1000000000, - "gasLimit": 99000000, - "gasUsed": 998505, - "smartContractResults": [ - { - "hash": "4c58801e77c57e88294f21018145662e2fb1698fd5f1a1cf7b6f81f073f5cd6c", - "nonce": 0, - "value": 2501000000000000000000, - "receiver": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", - "sender": "erd1s89rm6mv6xyct38r3vqadj74rmqunamhwyz7c84a6u9thedj2wus5nlchg", - "data": "createNewDelegationContract@00@00", - "prevTxHash": "af1581562830e36b0bfb12c618a4ee92d6b7f2e0aa84935432a44c9b63cc8daa", - "originalTxHash": "af1581562830e36b0bfb12c618a4ee92d6b7f2e0aa84935432a44c9b63cc8daa", - "gasLimit": 84900500, - "gasPrice": 1000000000 - }, - { - "hash": "94e678f400192eeae3c84b3125c9d45301db619a3ecbf9e7f46266a81a85ef51", - "nonce": 1, - "value": 299005000000000, - "receiver": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", - "sender": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", - "prevTxHash": "4c58801e77c57e88294f21018145662e2fb1698fd5f1a1cf7b6f81f073f5cd6c", - "originalTxHash": "af1581562830e36b0bfb12c618a4ee92d6b7f2e0aa84935432a44c9b63cc8daa", - "gasLimit": 0, - "gasPrice": 1000000000, - "returnMessage": "gas refund for relayer", - "operation": "transfer", - "isRefund": true - } - ], - "innerTransactions": [ - { - "nonce": 0, - "value": "2501000000000000000000", - "receiver": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", - "sender": "erd1s89rm6mv6xyct38r3vqadj74rmqunamhwyz7c84a6u9thedj2wus5nlchg", - "gasPrice": 1000000000, - "gasLimit": 85000000, - "data": "Y3JlYXRlTmV3RGVsZWdhdGlvbkNvbnRyYWN0QDAwQDAw", - "signature": "610493074d4e3ce0d8dcc5434cc67032f7e4acf3fd9f97525dba4865ba42408df8315824bf7b6268e2fa0d97fc51efe1a32f7928a799064a69d54bf063a19607", - "chainID": "chain", - "version": 2, - "relayer": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze" - } - ] -} \ No newline at end of file diff --git a/node/external/transactionAPI/unmarshaller.go b/node/external/transactionAPI/unmarshaller.go index bc997cdf042..c9526217f4f 100644 --- a/node/external/transactionAPI/unmarshaller.go +++ b/node/external/transactionAPI/unmarshaller.go @@ -13,8 +13,6 @@ import ( "github.com/multiversx/mx-chain-go/sharding" ) -const operationTransfer = "transfer" - type txUnmarshaller struct { shardCoordinator sharding.Coordinator addressPubKeyConverter core.PubkeyConverter @@ -88,25 +86,8 @@ func (tu *txUnmarshaller) unmarshalTransaction(txBytes []byte, txType transactio } apiTx = tu.prepareUnsignedTx(&tx) } - - isRelayedV3 := len(apiTx.InnerTransactions) > 0 - if isRelayedV3 { - apiTx.Operation = operationTransfer - for _, innerTx := range apiTx.InnerTransactions { - apiTx.Receivers = append(apiTx.Receivers, innerTx.Receiver) - - rcvBytes, errDecode := tu.addressPubKeyConverter.Decode(innerTx.Receiver) - if errDecode != nil { - log.Warn("bech32PubkeyConverter.Decode() failed while decoding innerTx.Receiver", "error", errDecode) - continue - } - - apiTx.ReceiversShardIDs = append(apiTx.ReceiversShardIDs, tu.shardCoordinator.ComputeId(rcvBytes)) - } - - apiTx.IsRelayed = true - - return apiTx, nil + if err != nil { + return nil, err } res := tu.dataFieldParser.Parse(apiTx.Data, apiTx.Tx.GetSndAddr(), apiTx.Tx.GetRcvAddr(), tu.shardCoordinator.NumberOfShards()) @@ -130,22 +111,21 @@ func (tu *txUnmarshaller) prepareNormalTx(tx *transaction.Transaction) *transact senderAddress := tu.addressPubKeyConverter.SilentEncode(tx.SndAddr, log) apiTx := &transaction.ApiTransactionResult{ - Tx: tx, - Type: string(transaction.TxTypeNormal), - Nonce: tx.Nonce, - Value: tx.Value.String(), - Receiver: receiverAddress, - ReceiverUsername: tx.RcvUserName, - Sender: senderAddress, - SenderUsername: tx.SndUserName, - GasPrice: tx.GasPrice, - GasLimit: tx.GasLimit, - Data: tx.Data, - Signature: hex.EncodeToString(tx.Signature), - Options: tx.Options, - Version: tx.Version, - ChainID: string(tx.ChainID), - InnerTransactions: tu.prepareInnerTxs(tx), + Tx: tx, + Type: string(transaction.TxTypeNormal), + Nonce: tx.Nonce, + Value: tx.Value.String(), + Receiver: receiverAddress, + ReceiverUsername: tx.RcvUserName, + Sender: senderAddress, + SenderUsername: tx.SndUserName, + GasPrice: tx.GasPrice, + GasLimit: tx.GasLimit, + Data: tx.Data, + Signature: hex.EncodeToString(tx.Signature), + Options: tx.Options, + Version: tx.Version, + ChainID: string(tx.ChainID), } if len(tx.GuardianAddr) > 0 { @@ -153,72 +133,29 @@ func (tu *txUnmarshaller) prepareNormalTx(tx *transaction.Transaction) *transact apiTx.GuardianSignature = hex.EncodeToString(tx.GuardianSignature) } - if len(tx.RelayerAddr) > 0 { - apiTx.RelayerAddress = tu.addressPubKeyConverter.SilentEncode(tx.RelayerAddr, log) - } - return apiTx } -func (tu *txUnmarshaller) prepareInnerTxs(tx *transaction.Transaction) []*transaction.FrontendTransaction { - if len(tx.InnerTransactions) == 0 { - return nil - } - - innerTxs := make([]*transaction.FrontendTransaction, 0, len(tx.InnerTransactions)) - for _, innerTx := range tx.InnerTransactions { - frontEndTx := &transaction.FrontendTransaction{ - Nonce: innerTx.Nonce, - Value: innerTx.Value.String(), - Receiver: tu.addressPubKeyConverter.SilentEncode(innerTx.RcvAddr, log), - Sender: tu.addressPubKeyConverter.SilentEncode(innerTx.SndAddr, log), - SenderUsername: innerTx.SndUserName, - ReceiverUsername: innerTx.RcvUserName, - GasPrice: innerTx.GasPrice, - GasLimit: innerTx.GasLimit, - Data: innerTx.Data, - Signature: hex.EncodeToString(innerTx.Signature), - ChainID: string(innerTx.ChainID), - Version: innerTx.Version, - Options: innerTx.Options, - } - - if len(innerTx.GuardianAddr) > 0 { - frontEndTx.GuardianAddr = tu.addressPubKeyConverter.SilentEncode(innerTx.GuardianAddr, log) - frontEndTx.GuardianSignature = hex.EncodeToString(innerTx.GuardianSignature) - } - - if len(innerTx.RelayerAddr) > 0 { - frontEndTx.Relayer = tu.addressPubKeyConverter.SilentEncode(innerTx.RelayerAddr, log) - } - - innerTxs = append(innerTxs, frontEndTx) - } - - return innerTxs -} - func (tu *txUnmarshaller) prepareInvalidTx(tx *transaction.Transaction) *transaction.ApiTransactionResult { receiverAddress := tu.addressPubKeyConverter.SilentEncode(tx.RcvAddr, log) senderAddress := tu.addressPubKeyConverter.SilentEncode(tx.SndAddr, log) apiTx := &transaction.ApiTransactionResult{ - Tx: tx, - Type: string(transaction.TxTypeInvalid), - Nonce: tx.Nonce, - Value: tx.Value.String(), - Receiver: receiverAddress, - ReceiverUsername: tx.RcvUserName, - Sender: senderAddress, - SenderUsername: tx.SndUserName, - GasPrice: tx.GasPrice, - GasLimit: tx.GasLimit, - Data: tx.Data, - Signature: hex.EncodeToString(tx.Signature), - Options: tx.Options, - Version: tx.Version, - ChainID: string(tx.ChainID), - InnerTransactions: tu.prepareInnerTxs(tx), + Tx: tx, + Type: string(transaction.TxTypeInvalid), + Nonce: tx.Nonce, + Value: tx.Value.String(), + Receiver: receiverAddress, + ReceiverUsername: tx.RcvUserName, + Sender: senderAddress, + SenderUsername: tx.SndUserName, + GasPrice: tx.GasPrice, + GasLimit: tx.GasLimit, + Data: tx.Data, + Signature: hex.EncodeToString(tx.Signature), + Options: tx.Options, + Version: tx.Version, + ChainID: string(tx.ChainID), } if len(tx.GuardianAddr) > 0 { @@ -226,10 +163,6 @@ func (tu *txUnmarshaller) prepareInvalidTx(tx *transaction.Transaction) *transac apiTx.GuardianSignature = hex.EncodeToString(tx.GuardianSignature) } - if len(tx.RelayerAddr) > 0 { - apiTx.RelayerAddress = tu.addressPubKeyConverter.SilentEncode(tx.RelayerAddr, log) - } - return apiTx } diff --git a/node/metrics/metrics.go b/node/metrics/metrics.go index bc84198eca5..7d828d26394 100644 --- a/node/metrics/metrics.go +++ b/node/metrics/metrics.go @@ -121,7 +121,6 @@ func InitConfigMetrics( appStatusHandler.SetUInt64Value(common.MetricReturnDataToLastTransferEnableEpoch, uint64(enableEpochs.ReturnDataToLastTransferEnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricSenderInOutTransferEnableEpoch, uint64(enableEpochs.SenderInOutTransferEnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricRelayedTransactionsV2EnableEpoch, uint64(enableEpochs.RelayedTransactionsV2EnableEpoch)) - appStatusHandler.SetUInt64Value(common.MetricRelayedTransactionsV3EnableEpoch, uint64(enableEpochs.RelayedTransactionsV3EnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricFixRelayedBaseCostEnableEpoch, uint64(enableEpochs.FixRelayedBaseCostEnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricUnbondTokensV2EnableEpoch, uint64(enableEpochs.UnbondTokensV2EnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricSaveJailedAlwaysEnableEpoch, uint64(enableEpochs.SaveJailedAlwaysEnableEpoch)) diff --git a/node/metrics/metrics_test.go b/node/metrics/metrics_test.go index bec9f099923..1aa3bd7be2e 100644 --- a/node/metrics/metrics_test.go +++ b/node/metrics/metrics_test.go @@ -208,10 +208,9 @@ func TestInitConfigMetrics(t *testing.T) { EGLDInMultiTransferEnableEpoch: 101, CryptoOpcodesV2EnableEpoch: 102, ScToScLogEventEnableEpoch: 103, - RelayedTransactionsV3EnableEpoch: 104, - FixRelayedBaseCostEnableEpoch: 105, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 106, - FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 107, + FixRelayedBaseCostEnableEpoch: 104, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 105, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 106, MaxNodesChangeEnableEpoch: []config.MaxNodesChangeConfig{ { EpochEnable: 0, @@ -330,10 +329,9 @@ func TestInitConfigMetrics(t *testing.T) { "erd_egld_in_multi_transfer_enable_epoch": uint32(101), "erd_crypto_opcodes_v2_enable_epoch": uint32(102), "erd_set_sc_to_sc_log_event_enable_epoch": uint32(103), - "erd_relayed_transactions_v3_enable_epoch": uint32(104), - "erd_fix_relayed_base_cost_enable_epoch": uint32(105), - "erd_multi_esdt_transfer_execute_by_user_enable_epoch": uint32(106), - "erd_fix_relayed_move_balance_to_non_payable_sc_enable_epoch": uint32(107), + "erd_fix_relayed_base_cost_enable_epoch": uint32(104), + "erd_multi_esdt_transfer_execute_by_user_enable_epoch": uint32(105), + "erd_fix_relayed_move_balance_to_non_payable_sc_enable_epoch": uint32(106), "erd_max_nodes_change_enable_epoch": nil, "erd_total_supply": "12345", "erd_hysteresis": "0.100000", diff --git a/node/node.go b/node/node.go index 7331b9d44ca..a652e80be60 100644 --- a/node/node.go +++ b/node/node.go @@ -798,8 +798,6 @@ func (n *Node) commonTransactionValidation( enableSignWithTxHash, n.coreComponents.TxSignHasher(), n.coreComponents.TxVersionChecker(), - n.coreComponents.EnableEpochsHandler(), - n.processComponents.RelayedTxV3Processor(), ) if err != nil { return nil, nil, err @@ -893,20 +891,19 @@ func (n *Node) CreateTransaction(txArgs *external.ArgsCreateTransaction) (*trans } tx := &transaction.Transaction{ - Nonce: txArgs.Nonce, - Value: valAsBigInt, - RcvAddr: receiverAddress, - RcvUserName: txArgs.ReceiverUsername, - SndAddr: senderAddress, - SndUserName: txArgs.SenderUsername, - GasPrice: txArgs.GasPrice, - GasLimit: txArgs.GasLimit, - Data: txArgs.DataField, - Signature: signatureBytes, - ChainID: []byte(txArgs.ChainID), - Version: txArgs.Version, - Options: txArgs.Options, - InnerTransactions: txArgs.InnerTransactions, + Nonce: txArgs.Nonce, + Value: valAsBigInt, + RcvAddr: receiverAddress, + RcvUserName: txArgs.ReceiverUsername, + SndAddr: senderAddress, + SndUserName: txArgs.SenderUsername, + GasPrice: txArgs.GasPrice, + GasLimit: txArgs.GasLimit, + Data: txArgs.DataField, + Signature: signatureBytes, + ChainID: []byte(txArgs.ChainID), + Version: txArgs.Version, + Options: txArgs.Options, } if len(txArgs.Guardian) > 0 { @@ -916,13 +913,6 @@ func (n *Node) CreateTransaction(txArgs *external.ArgsCreateTransaction) (*trans } } - if len(txArgs.Relayer) > 0 { - tx.RelayerAddr, err = addrPubKeyConverter.Decode(txArgs.Relayer) - if err != nil { - return nil, nil, errors.New("could not create relayer address from provided param") - } - } - var txHash []byte txHash, err = core.CalculateHash(n.coreComponents.InternalMarshalizer(), n.coreComponents.Hasher(), tx) if err != nil { diff --git a/node/node_test.go b/node/node_test.go index b584dc2370b..319890a5d0d 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -61,7 +61,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/mainFactoryMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" "github.com/multiversx/mx-chain-go/testscommon/stakingcommon" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" @@ -1851,22 +1850,21 @@ func TestGenerateTransaction_CorrectParamsShouldNotError(t *testing.T) { func getDefaultTransactionArgs() *external.ArgsCreateTransaction { return &external.ArgsCreateTransaction{ - Nonce: uint64(0), - Value: new(big.Int).SetInt64(10).String(), - Receiver: "rcv", - ReceiverUsername: []byte("rcvrUsername"), - Sender: "snd", - SenderUsername: []byte("sndrUsername"), - GasPrice: uint64(10), - GasLimit: uint64(20), - DataField: []byte("-"), - SignatureHex: hex.EncodeToString(bytes.Repeat([]byte{0}, 10)), - ChainID: "chainID", - Version: 1, - Options: 0, - Guardian: "", - GuardianSigHex: "", - InnerTransactions: nil, + Nonce: uint64(0), + Value: new(big.Int).SetInt64(10).String(), + Receiver: "rcv", + ReceiverUsername: []byte("rcvrUsername"), + Sender: "snd", + SenderUsername: []byte("sndrUsername"), + GasPrice: uint64(10), + GasLimit: uint64(20), + DataField: []byte("-"), + SignatureHex: hex.EncodeToString(bytes.Repeat([]byte{0}, 10)), + ChainID: "chainID", + Version: 1, + Options: 0, + Guardian: "", + GuardianSigHex: "", } } @@ -5297,7 +5295,6 @@ func getDefaultProcessComponents() *factoryMock.ProcessComponentsMock { TxsSenderHandlerField: &txsSenderMock.TxsSenderHandlerMock{}, ScheduledTxsExecutionHandlerInternal: &testscommon.ScheduledTxsExecutionStub{}, HistoryRepositoryInternal: &dblookupext.HistoryRepositoryStub{}, - RelayedTxV3ProcessorField: &processMocks.RelayedTxV3ProcessorMock{}, } } diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index dccf0366b23..e0d56acbde3 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -135,11 +135,6 @@ func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *trans feeInfo.SetFee(initialPaidFee) } - if len(txHandler.GetUserTransactions()) > 0 { - tep.prepareRelayedTxV3WithResults(txHashHex, txWithResult) - continue - } - totalFee, isRelayed := tep.getFeeOfRelayed(txWithResult) isRelayedAfterFix := isRelayed && isFeeFixActive if isRelayedAfterFix { @@ -155,7 +150,6 @@ func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *trans func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWithResults *transactionWithResults, isRelayedAfterFix bool) { hasRefund := false - totalRefunds := big.NewInt(0) for _, scrHandler := range txWithResults.scrs { scr, ok := scrHandler.GetTxHandler().(*smartContractResult.SmartContractResult) if !ok { @@ -163,21 +157,15 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWi } if isSCRForSenderWithRefund(scr, txHashHex, txWithResults.GetTxHandler()) || isRefundForRelayed(scr, txWithResults.GetTxHandler()) { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), scr.Value) + + txWithResults.GetFeeInfo().SetGasUsed(gasUsed) + txWithResults.GetFeeInfo().SetFee(fee) hasRefund = true - totalRefunds.Add(totalRefunds, scr.Value) + break } } - if totalRefunds.Cmp(big.NewInt(0)) > 0 { - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), totalRefunds) - txWithResults.GetFeeInfo().SetGasUsed(gasUsed) - txWithResults.GetFeeInfo().SetFee(fee) - } - - if isRelayedAfterFix { - return - } - tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefund) } @@ -243,31 +231,6 @@ func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transact return big.NewInt(0).Add(fee, innerFee), true } -func (tep *transactionsFeeProcessor) prepareRelayedTxV3WithResults(txHashHex string, txWithResults *transactionWithResults) { - refundsValue := big.NewInt(0) - for _, scrHandler := range txWithResults.scrs { - scr, ok := scrHandler.GetTxHandler().(*smartContractResult.SmartContractResult) - if !ok { - continue - } - - if !isRefundForRelayed(scr, txWithResults.GetTxHandler()) { - continue - } - - refundsValue.Add(refundsValue, scr.Value) - } - - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), refundsValue) - - txWithResults.GetFeeInfo().SetGasUsed(gasUsed) - txWithResults.GetFeeInfo().SetFee(fee) - - hasRefunds := refundsValue.Cmp(big.NewInt(0)) == 1 - tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefunds) - -} - func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( txHashHex string, txWithResults *transactionWithResults, diff --git a/process/block/preprocess/gasComputation.go b/process/block/preprocess/gasComputation.go index 9888917b7f3..628c6de455f 100644 --- a/process/block/preprocess/gasComputation.go +++ b/process/block/preprocess/gasComputation.go @@ -426,7 +426,7 @@ func (gc *gasComputation) computeGasProvidedByTxV1( } func (gc *gasComputation) isRelayedTx(txType process.TransactionType) bool { - return txType == process.RelayedTx || txType == process.RelayedTxV2 || txType == process.RelayedTxV3 + return txType == process.RelayedTx || txType == process.RelayedTxV2 } // IsInterfaceNil returns true if there is no value under the interface diff --git a/process/constants.go b/process/constants.go index 44101f50b7c..f75e7b882ee 100644 --- a/process/constants.go +++ b/process/constants.go @@ -36,8 +36,6 @@ const ( RelayedTx // RelayedTxV2 defines the ID of a slim relayed transaction version RelayedTxV2 - // RelayedTxV3 defines the ID of a relayed v3 transaction - RelayedTxV3 // RewardTx defines ID of a reward transaction RewardTx // InvalidTransaction defines unknown transaction type @@ -58,8 +56,6 @@ func (transactionType TransactionType) String() string { return "RelayedTx" case RelayedTxV2: return "RelayedTxV2" - case RelayedTxV3: - return "RelayedTxV3" case RewardTx: return "RewardTx" case InvalidTransaction: diff --git a/process/coordinator/transactionType.go b/process/coordinator/transactionType.go index d754da2c34d..32081a1ac0e 100644 --- a/process/coordinator/transactionType.go +++ b/process/coordinator/transactionType.go @@ -90,11 +90,6 @@ func (tth *txTypeHandler) ComputeTransactionType(tx data.TransactionHandler) (pr } return process.InvalidTransaction, process.InvalidTransaction } - - if tth.isRelayedTransactionV3(tx) { - return process.RelayedTxV3, process.RelayedTxV3 - } - if len(tx.GetData()) == 0 { return process.MoveBalance, process.MoveBalance } @@ -195,10 +190,6 @@ func (tth *txTypeHandler) isRelayedTransactionV2(functionName string) bool { return functionName == core.RelayedTransactionV2 } -func (tth *txTypeHandler) isRelayedTransactionV3(tx data.TransactionHandler) bool { - return len(tx.GetUserTransactions()) != 0 -} - func (tth *txTypeHandler) isDestAddressEmpty(tx data.TransactionHandler) bool { isEmptyAddress := bytes.Equal(tx.GetRcvAddr(), make([]byte, tth.pubkeyConv.Len())) return isEmptyAddress diff --git a/process/coordinator/transactionType_test.go b/process/coordinator/transactionType_test.go index 9739075d847..918b6069212 100644 --- a/process/coordinator/transactionType_test.go +++ b/process/coordinator/transactionType_test.go @@ -466,32 +466,6 @@ func TestTxTypeHandler_ComputeTransactionTypeRelayedV2Func(t *testing.T) { assert.Equal(t, process.RelayedTxV2, txTypeCross) } -func TestTxTypeHandler_ComputeTransactionTypeRelayedV3(t *testing.T) { - t.Parallel() - - tx := &transaction.Transaction{} - tx.Nonce = 0 - tx.SndAddr = []byte("000") - tx.RcvAddr = []byte("001") - tx.Value = big.NewInt(45) - tx.InnerTransactions = []*transaction.Transaction{{Nonce: 1}} - - arg := createMockArguments() - arg.PubkeyConverter = &testscommon.PubkeyConverterStub{ - LenCalled: func() int { - return len(tx.RcvAddr) - }, - } - tth, err := NewTxTypeHandler(arg) - - assert.NotNil(t, tth) - assert.Nil(t, err) - - txTypeIn, txTypeCross := tth.ComputeTransactionType(tx) - assert.Equal(t, process.RelayedTxV3, txTypeIn) - assert.Equal(t, process.RelayedTxV3, txTypeCross) -} - func TestTxTypeHandler_ComputeTransactionTypeForSCRCallBack(t *testing.T) { t.Parallel() diff --git a/process/disabled/failedTxLogsAccumulator.go b/process/disabled/failedTxLogsAccumulator.go deleted file mode 100644 index 3bd3f01cd69..00000000000 --- a/process/disabled/failedTxLogsAccumulator.go +++ /dev/null @@ -1,33 +0,0 @@ -package disabled - -import ( - "github.com/multiversx/mx-chain-core-go/data" - vmcommon "github.com/multiversx/mx-chain-vm-common-go" -) - -type failedTxLogsAccumulator struct { -} - -// NewFailedTxLogsAccumulator returns a new instance of disabled failedTxLogsAccumulator -func NewFailedTxLogsAccumulator() *failedTxLogsAccumulator { - return &failedTxLogsAccumulator{} -} - -// GetLogs returns false as it is disabled -func (accumulator *failedTxLogsAccumulator) GetLogs(_ []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) { - return nil, nil, false -} - -// SaveLogs returns nil as it is disabled -func (accumulator *failedTxLogsAccumulator) SaveLogs(_ []byte, _ data.TransactionHandler, _ []*vmcommon.LogEntry) error { - return nil -} - -// Remove does nothing as it is disabled -func (accumulator *failedTxLogsAccumulator) Remove(_ []byte) { -} - -// IsInterfaceNil returns true if there is no value under the interface -func (accumulator *failedTxLogsAccumulator) IsInterfaceNil() bool { - return accumulator == nil -} diff --git a/process/disabled/relayedTxV3Processor.go b/process/disabled/relayedTxV3Processor.go deleted file mode 100644 index ddabd2753c8..00000000000 --- a/process/disabled/relayedTxV3Processor.go +++ /dev/null @@ -1,23 +0,0 @@ -package disabled - -import ( - "github.com/multiversx/mx-chain-core-go/data/transaction" -) - -type relayedTxV3Processor struct { -} - -// NewRelayedTxV3Processor returns a new instance of disabled relayedTxV3Processor -func NewRelayedTxV3Processor() *relayedTxV3Processor { - return &relayedTxV3Processor{} -} - -// CheckRelayedTx returns nil as it is disabled -func (proc *relayedTxV3Processor) CheckRelayedTx(_ *transaction.Transaction) error { - return nil -} - -// IsInterfaceNil returns true if there is no value under the interface -func (proc *relayedTxV3Processor) IsInterfaceNil() bool { - return proc == nil -} diff --git a/process/economics/economicsData.go b/process/economics/economicsData.go index 170377e62d3..5b7ce045237 100644 --- a/process/economics/economicsData.go +++ b/process/economics/economicsData.go @@ -13,7 +13,6 @@ import ( "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/process" - "github.com/multiversx/mx-chain-go/process/disabled" "github.com/multiversx/mx-chain-go/statusHandler" logger "github.com/multiversx/mx-chain-logger-go" ) @@ -35,8 +34,6 @@ type economicsData struct { statusHandler core.AppStatusHandler enableEpochsHandler common.EnableEpochsHandler txVersionHandler process.TxVersionCheckerHandler - txTypeHandler process.TxTypeHandler - mutTxTypeHandler sync.RWMutex mut sync.RWMutex } @@ -78,7 +75,6 @@ func NewEconomicsData(args ArgsNewEconomicsData) (*economicsData, error) { statusHandler: statusHandler.NewNilStatusHandler(), enableEpochsHandler: args.EnableEpochsHandler, txVersionHandler: args.TxVersionChecker, - txTypeHandler: disabled.NewTxTypeHandler(), } ed.yearSettings = make(map[uint32]*config.YearSetting) @@ -141,19 +137,6 @@ func (ed *economicsData) SetStatusHandler(statusHandler core.AppStatusHandler) e return ed.rewardsConfigHandler.setStatusHandler(statusHandler) } -// SetTxTypeHandler sets the provided tx type handler -func (ed *economicsData) SetTxTypeHandler(txTypeHandler process.TxTypeHandler) error { - if check.IfNil(txTypeHandler) { - return process.ErrNilTxTypeHandler - } - - ed.mutTxTypeHandler.Lock() - ed.txTypeHandler = txTypeHandler - ed.mutTxTypeHandler.Unlock() - - return nil -} - // LeaderPercentage returns leader reward percentage func (ed *economicsData) LeaderPercentage() float64 { currentEpoch := ed.enableEpochsHandler.GetCurrentEpoch() @@ -302,11 +285,6 @@ func (ed *economicsData) ComputeTxFee(tx data.TransactionWithFeeHandler) *big.In // ComputeTxFeeInEpoch computes the provided transaction's fee in a specific epoch func (ed *economicsData) ComputeTxFeeInEpoch(tx data.TransactionWithFeeHandler, epoch uint32) *big.Int { - if len(tx.GetUserTransactions()) > 0 { - _, totalFee, _ := ed.ComputeRelayedTxFees(tx) - return totalFee - } - if ed.enableEpochsHandler.IsFlagEnabledInEpoch(common.GasPriceModifierFlag, epoch) { if isSmartContractResult(tx) { return ed.ComputeFeeForProcessingInEpoch(tx, tx.GetGasLimit(), epoch) @@ -330,56 +308,6 @@ func (ed *economicsData) ComputeTxFeeInEpoch(tx data.TransactionWithFeeHandler, return ed.ComputeMoveBalanceFeeInEpoch(tx, epoch) } -// ComputeRelayedTxFees returns the both the total fee for the entire relayed tx and the relayed only fee -func (ed *economicsData) ComputeRelayedTxFees(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - innerTxs := tx.GetUserTransactions() - if len(innerTxs) == 0 { - return big.NewInt(0), big.NewInt(0), process.ErrEmptyInnerTransactions - } - - feesForInnerTxs := ed.getTotalFeesRequiredForInnerTxs(innerTxs) - - relayerUnguardedMoveBalanceFee := core.SafeMul(ed.GasPriceForMove(tx), ed.MinGasLimit()) - relayerTotalMoveBalanceFee := ed.ComputeMoveBalanceFee(tx) - relayerMoveBalanceFeeDiff := big.NewInt(0).Sub(relayerTotalMoveBalanceFee, relayerUnguardedMoveBalanceFee) - - relayerFee := big.NewInt(0).Mul(relayerUnguardedMoveBalanceFee, big.NewInt(int64(len(innerTxs)))) - relayerFee.Add(relayerFee, relayerMoveBalanceFeeDiff) // add the difference in case of guarded relayed tx - - totalFee := big.NewInt(0).Add(relayerFee, feesForInnerTxs) - - return relayerFee, totalFee, nil -} - -func (ed *economicsData) getTotalFeesRequiredForInnerTxs(innerTxs []data.TransactionHandler) *big.Int { - totalFees := big.NewInt(0) - for _, innerTx := range innerTxs { - if ed.isMoveBalance(innerTx) { - innerTxFee := ed.ComputeMoveBalanceFee(innerTx) - totalFees.Add(totalFees, innerTxFee) - - continue - } - - gasToUse := innerTx.GetGasLimit() - ed.ComputeGasLimit(innerTx) - moveBalanceUserFee := ed.ComputeMoveBalanceFee(innerTx) - processingUserFee := ed.ComputeFeeForProcessing(innerTx, gasToUse) - innerTxFee := big.NewInt(0).Add(moveBalanceUserFee, processingUserFee) - - totalFees.Add(totalFees, innerTxFee) - } - - return totalFees -} - -func (ed *economicsData) isMoveBalance(tx data.TransactionHandler) bool { - ed.mutTxTypeHandler.RLock() - _, dstTxType := ed.txTypeHandler.ComputeTransactionType(tx) - ed.mutTxTypeHandler.RUnlock() - - return dstTxType == process.MoveBalance -} - // SplitTxGasInCategories returns the gas split per categories func (ed *economicsData) SplitTxGasInCategories(tx data.TransactionWithFeeHandler) (gasLimitMove, gasLimitProcess uint64) { currentEpoch := ed.enableEpochsHandler.GetCurrentEpoch() @@ -590,18 +518,6 @@ func (ed *economicsData) ComputeGasUsedAndFeeBasedOnRefundValueInEpoch(tx data.T txFee := ed.ComputeTxFeeInEpoch(tx, epoch) - if len(tx.GetUserTransactions()) > 0 { - txFeeAfterRefund := txFee.Sub(txFee, refundValue) - - gasPriceForProcessing := ed.GasPriceForProcessingInEpoch(tx, epoch) - gasUnitsRefunded := refundValue.Uint64() / gasPriceForProcessing - - gasUnitsConsideredForInitialFee := ed.computeRelayedTxV3MinGasLimit(tx) - gasUnitsUsed := gasUnitsConsideredForInitialFee - gasUnitsRefunded - - return gasUnitsUsed, txFeeAfterRefund - } - isPenalizedTooMuchGasFlagEnabled := ed.enableEpochsHandler.IsFlagEnabledInEpoch(common.PenalizedTooMuchGasFlag, epoch) isGasPriceModifierFlagEnabled := ed.enableEpochsHandler.IsFlagEnabledInEpoch(common.GasPriceModifierFlag, epoch) flagCorrectTxFee := !isPenalizedTooMuchGasFlagEnabled && !isGasPriceModifierFlagEnabled @@ -689,20 +605,6 @@ func (ed *economicsData) ComputeGasLimitBasedOnBalanceInEpoch(tx data.Transactio return totalGasLimit, nil } -func (ed *economicsData) computeRelayedTxV3MinGasLimit(tx data.TransactionWithFeeHandler) uint64 { - relayedTxGasLimit := ed.ComputeGasLimit(tx) - relayedTxMinGasLimit := ed.MinGasLimit() - relayedTxGasLimitDiff := relayedTxGasLimit - relayedTxMinGasLimit // this may be positive if the relayed tx is guarded - - innerTxs := tx.GetUserTransactions() - totalGasLimit := relayedTxGasLimitDiff + relayedTxMinGasLimit*uint64(len(innerTxs)) - for _, innerTx := range innerTxs { - totalGasLimit += innerTx.GetGasLimit() - } - - return totalGasLimit -} - // IsInterfaceNil returns true if there is no value under the interface func (ed *economicsData) IsInterfaceNil() bool { return ed == nil diff --git a/process/economics/economicsData_test.go b/process/economics/economicsData_test.go index f1a66e25dcd..1f2c913a826 100644 --- a/process/economics/economicsData_test.go +++ b/process/economics/economicsData_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" - "github.com/multiversx/mx-chain-core-go/data" "github.com/multiversx/mx-chain-core-go/data/smartContractResult" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/common" @@ -1281,39 +1280,6 @@ func TestEconomicsData_ComputeGasUsedAndFeeBasedOnRefundValueSpecialBuiltInTooMu require.Equal(t, expectedFee, fee) } -func TestEconomicsData_ComputeGasUsedAndFeeBasedOnRefundValueRelayedV3(t *testing.T) { - t.Parallel() - - economicData, _ := economics.NewEconomicsData(createArgsForEconomicsDataRealFees()) - tx := &transaction.Transaction{ - GasPrice: 1000000000, - GasLimit: 99000000, - InnerTransactions: []*transaction.Transaction{ - { - GasPrice: 1000000000, - GasLimit: 85000000, - Data: []byte("createNewDelegationContract@00@00"), - }, - { - GasPrice: 1000000000, - GasLimit: 50000, - }, - { - GasPrice: 1000000000, - GasLimit: 50000, - }, - }, - } - - expectedGasUsed := uint64(55349500) - expectedFee, _ := big.NewInt(0).SetString("899500000000000", 10) - - refundValue, _ := big.NewInt(0).SetString("299005000000000", 10) - gasUsed, fee := economicData.ComputeGasUsedAndFeeBasedOnRefundValue(tx, refundValue) - require.Equal(t, expectedGasUsed, gasUsed) - require.Equal(t, expectedFee, fee) -} - func TestEconomicsData_ComputeGasLimitBasedOnBalance(t *testing.T) { t.Parallel() @@ -1655,102 +1621,3 @@ func TestEconomicsData_RewardsTopUpFactor(t *testing.T) { value := economicsData.RewardsTopUpFactor() assert.Equal(t, topUpFactor, value) } - -func TestEconomicsData_ComputeRelayedTxFees(t *testing.T) { - t.Parallel() - - args := createArgsForEconomicsData(1) - minGasLimit, _ := strconv.Atoi(args.Economics.FeeSettings.GasLimitSettings[0].MinGasLimit) - tx := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(0), - RcvAddr: []byte("rel"), - SndAddr: []byte("rel"), - GasPrice: 1, - GasLimit: uint64(minGasLimit) * 4, - InnerTransactions: []*transaction.Transaction{ - { - Nonce: 0, - Value: big.NewInt(1), - RcvAddr: []byte("rcv1"), - SndAddr: []byte("snd1"), - GasPrice: 1, - GasLimit: uint64(minGasLimit), - RelayerAddr: []byte("rel"), - }, - { - Nonce: 0, - Value: big.NewInt(1), - RcvAddr: []byte("rcv1"), - SndAddr: []byte("snd2"), - GasPrice: 1, - GasLimit: uint64(minGasLimit), - RelayerAddr: []byte("rel"), - }, - }, - } - t.Run("empty inner txs should error", func(t *testing.T) { - t.Parallel() - - economicsData, _ := economics.NewEconomicsData(args) - - txCopy := *tx - txCopy.InnerTransactions = []*transaction.Transaction{} - relayerFee, totalFee, err := economicsData.ComputeRelayedTxFees(&txCopy) - require.Equal(t, process.ErrEmptyInnerTransactions, err) - require.Equal(t, big.NewInt(0), relayerFee) - require.Equal(t, big.NewInt(0), totalFee) - }) - t.Run("should work unguarded", func(t *testing.T) { - t.Parallel() - - economicsData, _ := economics.NewEconomicsData(args) - - _ = economicsData.SetTxTypeHandler(&testscommon.TxTypeHandlerMock{ - ComputeTransactionTypeCalled: func(tx data.TransactionHandler) (process.TransactionType, process.TransactionType) { - return process.MoveBalance, process.MoveBalance - }, - }) - - relayerFee, totalFee, err := economicsData.ComputeRelayedTxFees(tx) - require.NoError(t, err) - expectedRelayerFee := big.NewInt(int64(2 * uint64(minGasLimit) * tx.GetGasPrice())) // 2 move balance - require.Equal(t, expectedRelayerFee, relayerFee) - require.Equal(t, big.NewInt(int64(tx.GetGasLimit()*tx.GetGasPrice())), totalFee) - }) - t.Run("should work guarded", func(t *testing.T) { - t.Parallel() - - argsLocal := createArgsForEconomicsData(1) - argsLocal.TxVersionChecker = &testscommon.TxVersionCheckerStub{ - IsGuardedTransactionCalled: func(tx *transaction.Transaction) bool { - return len(tx.InnerTransactions) > 0 // only the relayed tx is guarded - }, - } - economicsData, _ := economics.NewEconomicsData(argsLocal) - - extraGasLimitGuardedTx, _ := strconv.Atoi(argsLocal.Economics.FeeSettings.GasLimitSettings[0].ExtraGasLimitGuardedTx) - - txCopy := *tx - txCopy.GasLimit += uint64(extraGasLimitGuardedTx) - relayerFee, totalFee, err := economicsData.ComputeRelayedTxFees(&txCopy) - require.NoError(t, err) - expectedRelayerFee := big.NewInt(int64(2*uint64(minGasLimit)*txCopy.GetGasPrice() + uint64(extraGasLimitGuardedTx)*txCopy.GetGasPrice())) // 2 move balance - require.Equal(t, expectedRelayerFee, relayerFee) - require.Equal(t, big.NewInt(int64(txCopy.GetGasLimit()*txCopy.GetGasPrice())), totalFee) - }) -} - -func TestEconomicsData_SetTxTypeHandler(t *testing.T) { - t.Parallel() - - args := createArgsForEconomicsData(1) - economicsData, _ := economics.NewEconomicsData(args) - assert.NotNil(t, economicsData) - - err := economicsData.SetTxTypeHandler(nil) - require.Equal(t, process.ErrNilTxTypeHandler, err) - - err = economicsData.SetTxTypeHandler(&testscommon.TxTypeHandlerMock{}) - require.NoError(t, err) -} diff --git a/process/errors.go b/process/errors.go index a4e426691bd..83e8095dcb3 100644 --- a/process/errors.go +++ b/process/errors.go @@ -1229,48 +1229,3 @@ var ErrNilSentSignatureTracker = errors.New("nil sent signature tracker") // ErrTransferAndExecuteByUserAddressesAreNil signals that transfer and execute by user addresses are nil var ErrTransferAndExecuteByUserAddressesAreNil = errors.New("transfer and execute by user addresses are nil") - -// ErrRelayedV3GasPriceMismatch signals that relayed v3 gas price is not equal with inner tx -var ErrRelayedV3GasPriceMismatch = errors.New("relayed tx v3 gas price mismatch") - -// ErrRelayedTxV3SenderDoesNotMatchReceiver signals that the sender of relayed tx v3 does not match the receiver -var ErrRelayedTxV3SenderDoesNotMatchReceiver = errors.New("relayed tx v3 sender does not match receiver") - -// ErrRelayedTxV3Disabled signals that the v3 version of relayed tx is disabled -var ErrRelayedTxV3Disabled = errors.New("relayed tx v3 is disabled") - -// ErrRelayedTxV3ZeroVal signals that the v3 version of relayed tx should be created with 0 as value -var ErrRelayedTxV3ZeroVal = errors.New("relayed tx v3 value should be 0") - -// ErrRelayedTxV3RelayerMismatch signals that the relayer address of the inner tx does not match the real relayer -var ErrRelayedTxV3RelayerMismatch = errors.New("relayed tx v3 relayer mismatch") - -// ErrRelayedTxV3GasLimitMismatch signals that relayed tx v3 gas limit is higher than user tx gas limit -var ErrRelayedTxV3GasLimitMismatch = errors.New("relayed tx v3 gas limit mismatch") - -// ErrNilRelayedTxV3Processor signals that a nil relayed tx v3 processor has been provided -var ErrNilRelayedTxV3Processor = errors.New("nil relayed tx v3 processor") - -// ErrRelayedTxV3SenderShardMismatch signals that the sender from inner transaction is from a different shard than relayer -var ErrRelayedTxV3SenderShardMismatch = errors.New("sender shard mismatch") - -// ErrNilRelayerAccount signals that a nil relayer accouont has been provided -var ErrNilRelayerAccount = errors.New("nil relayer account") - -// ErrRelayedTxV3TooManyInnerTransactions signals that too many inner transactions were provided -var ErrRelayedTxV3TooManyInnerTransactions = errors.New("too many inner transactions") - -// ErrConsumedFeesMismatch signals that the fees consumed from relayer do not match the inner transactions fees -var ErrConsumedFeesMismatch = errors.New("consumed fees mismatch") - -// ErrRelayedTxV3InvalidDataField signals that the data field is invalid -var ErrRelayedTxV3InvalidDataField = errors.New("invalid data field") - -// ErrMultipleRelayedTxTypesIsNotAllowed signals that multiple types of relayed tx is not allowed -var ErrMultipleRelayedTxTypesIsNotAllowed = errors.New("multiple relayed tx types is not allowed") - -// ErrNilFailedTxLogsAccumulator signals that a nil failed transaction logs accumulator has been provided -var ErrNilFailedTxLogsAccumulator = errors.New("nil failed transaction logs accumulator") - -// ErrEmptyInnerTransactions signals that the inner transactions slice is empty -var ErrEmptyInnerTransactions = errors.New("empty inner transactions") diff --git a/process/factory/interceptorscontainer/args.go b/process/factory/interceptorscontainer/args.go index 0d224b031ad..294e66290b3 100644 --- a/process/factory/interceptorscontainer/args.go +++ b/process/factory/interceptorscontainer/args.go @@ -43,5 +43,4 @@ type CommonInterceptorsContainerFactoryArgs struct { FullArchivePeerShardMapper process.PeerShardMapper HardforkTrigger heartbeat.HardforkTrigger NodeOperationMode common.NodeOperation - RelayedTxV3Processor process.RelayedTxV3Processor } diff --git a/process/factory/interceptorscontainer/metaInterceptorsContainerFactory.go b/process/factory/interceptorscontainer/metaInterceptorsContainerFactory.go index 31a4344b771..38d3e460bce 100644 --- a/process/factory/interceptorscontainer/metaInterceptorsContainerFactory.go +++ b/process/factory/interceptorscontainer/metaInterceptorsContainerFactory.go @@ -99,7 +99,6 @@ func NewMetaInterceptorsContainerFactory( SignaturesHandler: args.SignaturesHandler, HeartbeatExpiryTimespanInSec: args.HeartbeatExpiryTimespanInSec, PeerID: args.MainMessenger.ID(), - RelayedTxV3Processor: args.RelayedTxV3Processor, } base := &baseInterceptorsContainerFactory{ diff --git a/process/factory/interceptorscontainer/metaInterceptorsContainerFactory_test.go b/process/factory/interceptorscontainer/metaInterceptorsContainerFactory_test.go index b9124001264..fe853c32662 100644 --- a/process/factory/interceptorscontainer/metaInterceptorsContainerFactory_test.go +++ b/process/factory/interceptorscontainer/metaInterceptorsContainerFactory_test.go @@ -18,7 +18,6 @@ import ( dataRetrieverMock "github.com/multiversx/mx-chain-go/testscommon/dataRetriever" "github.com/multiversx/mx-chain-go/testscommon/economicsmocks" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" storageStubs "github.com/multiversx/mx-chain-go/testscommon/storage" @@ -708,6 +707,5 @@ func getArgumentsMeta( FullArchivePeerShardMapper: &p2pmocks.NetworkShardingCollectorStub{}, HardforkTrigger: &testscommon.HardforkTriggerStub{}, NodeOperationMode: common.NormalOperation, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, } } diff --git a/process/factory/interceptorscontainer/shardInterceptorsContainerFactory.go b/process/factory/interceptorscontainer/shardInterceptorsContainerFactory.go index 26224fbc152..beef288c54c 100644 --- a/process/factory/interceptorscontainer/shardInterceptorsContainerFactory.go +++ b/process/factory/interceptorscontainer/shardInterceptorsContainerFactory.go @@ -98,7 +98,6 @@ func NewShardInterceptorsContainerFactory( SignaturesHandler: args.SignaturesHandler, HeartbeatExpiryTimespanInSec: args.HeartbeatExpiryTimespanInSec, PeerID: args.MainMessenger.ID(), - RelayedTxV3Processor: args.RelayedTxV3Processor, } base := &baseInterceptorsContainerFactory{ diff --git a/process/factory/interceptorscontainer/shardInterceptorsContainerFactory_test.go b/process/factory/interceptorscontainer/shardInterceptorsContainerFactory_test.go index f802562ae35..677876311e9 100644 --- a/process/factory/interceptorscontainer/shardInterceptorsContainerFactory_test.go +++ b/process/factory/interceptorscontainer/shardInterceptorsContainerFactory_test.go @@ -22,7 +22,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" storageStubs "github.com/multiversx/mx-chain-go/testscommon/storage" @@ -733,6 +732,5 @@ func getArgumentsShard( MainPeerShardMapper: &p2pmocks.NetworkShardingCollectorStub{}, FullArchivePeerShardMapper: &p2pmocks.NetworkShardingCollectorStub{}, HardforkTrigger: &testscommon.HardforkTriggerStub{}, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, } } diff --git a/process/interceptors/factory/argInterceptedDataFactory.go b/process/interceptors/factory/argInterceptedDataFactory.go index 36ab4968375..37701a92f7a 100644 --- a/process/interceptors/factory/argInterceptedDataFactory.go +++ b/process/interceptors/factory/argInterceptedDataFactory.go @@ -57,5 +57,4 @@ type ArgInterceptedDataFactory struct { SignaturesHandler process.SignaturesHandler HeartbeatExpiryTimespanInSec int64 PeerID core.PeerID - RelayedTxV3Processor process.RelayedTxV3Processor } diff --git a/process/interceptors/factory/interceptedMetaHeaderDataFactory_test.go b/process/interceptors/factory/interceptedMetaHeaderDataFactory_test.go index d2ecc63e59d..e46692e6614 100644 --- a/process/interceptors/factory/interceptedMetaHeaderDataFactory_test.go +++ b/process/interceptors/factory/interceptedMetaHeaderDataFactory_test.go @@ -20,7 +20,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" - testProcessMocks "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" "github.com/stretchr/testify/assert" ) @@ -107,7 +106,6 @@ func createMockArgument( SignaturesHandler: &processMocks.SignaturesHandlerStub{}, HeartbeatExpiryTimespanInSec: 30, PeerID: "pid", - RelayedTxV3Processor: &testProcessMocks.RelayedTxV3ProcessorMock{}, } } diff --git a/process/interceptors/factory/interceptedTxDataFactory.go b/process/interceptors/factory/interceptedTxDataFactory.go index e2dc86e599c..563997c5066 100644 --- a/process/interceptors/factory/interceptedTxDataFactory.go +++ b/process/interceptors/factory/interceptedTxDataFactory.go @@ -31,7 +31,6 @@ type interceptedTxDataFactory struct { txSignHasher hashing.Hasher txVersionChecker process.TxVersionCheckerHandler enableEpochsHandler common.EnableEpochsHandler - relayedTxV3Processor process.RelayedTxV3Processor } // NewInterceptedTxDataFactory creates an instance of interceptedTxDataFactory @@ -108,7 +107,6 @@ func NewInterceptedTxDataFactory(argument *ArgInterceptedDataFactory) (*intercep txSignHasher: argument.CoreComponents.TxSignHasher(), txVersionChecker: argument.CoreComponents.TxVersionChecker(), enableEpochsHandler: argument.CoreComponents.EnableEpochsHandler(), - relayedTxV3Processor: argument.RelayedTxV3Processor, } return itdf, nil @@ -132,8 +130,6 @@ func (itdf *interceptedTxDataFactory) Create(buff []byte) (process.InterceptedDa itdf.enableEpochsHandler.IsFlagEnabled(common.TransactionSignedWithTxHashFlag), itdf.txSignHasher, itdf.txVersionChecker, - itdf.enableEpochsHandler, - itdf.relayedTxV3Processor, ) } diff --git a/process/interface.go b/process/interface.go index 8e943d0a44e..747103f26ca 100644 --- a/process/interface.go +++ b/process/interface.go @@ -699,7 +699,6 @@ type feeHandler interface { ComputeGasLimitInEpoch(tx data.TransactionWithFeeHandler, epoch uint32) uint64 ComputeGasUsedAndFeeBasedOnRefundValueInEpoch(tx data.TransactionWithFeeHandler, refundValue *big.Int, epoch uint32) (uint64, *big.Int) ComputeTxFeeBasedOnGasUsedInEpoch(tx data.TransactionWithFeeHandler, gasUsed uint64, epoch uint32) *big.Int - ComputeRelayedTxFees(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) } // TxGasHandler handles a transaction gas and gas cost @@ -726,7 +725,6 @@ type EconomicsDataHandler interface { rewardsHandler feeHandler SetStatusHandler(statusHandler core.AppStatusHandler) error - SetTxTypeHandler(txTypeHandler TxTypeHandler) error IsInterfaceNil() bool } @@ -1361,17 +1359,3 @@ type SentSignaturesTracker interface { ResetCountersForManagedBlockSigner(signerPk []byte) IsInterfaceNil() bool } - -// RelayedTxV3Processor defines a component able to check and process relayed transactions v3 -type RelayedTxV3Processor interface { - CheckRelayedTx(tx *transaction.Transaction) error - IsInterfaceNil() bool -} - -// FailedTxLogsAccumulator defines a component able to accumulate logs during a relayed tx execution -type FailedTxLogsAccumulator interface { - GetLogs(txHash []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) - SaveLogs(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error - Remove(txHash []byte) - IsInterfaceNil() bool -} diff --git a/process/smartContract/processProxy/processProxy.go b/process/smartContract/processProxy/processProxy.go index a36a5fbd4f4..c64db4791a4 100644 --- a/process/smartContract/processProxy/processProxy.go +++ b/process/smartContract/processProxy/processProxy.go @@ -50,30 +50,29 @@ func NewSmartContractProcessorProxy(args scrCommon.ArgsNewSmartContractProcessor proxy := &scProcessorProxy{ args: scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: args.VmContainer, - ArgsParser: args.ArgsParser, - Hasher: args.Hasher, - Marshalizer: args.Marshalizer, - AccountsDB: args.AccountsDB, - BlockChainHook: args.BlockChainHook, - BuiltInFunctions: args.BuiltInFunctions, - PubkeyConv: args.PubkeyConv, - ShardCoordinator: args.ShardCoordinator, - ScrForwarder: args.ScrForwarder, - TxFeeHandler: args.TxFeeHandler, - EconomicsFee: args.EconomicsFee, - TxTypeHandler: args.TxTypeHandler, - GasHandler: args.GasHandler, - GasSchedule: args.GasSchedule, - TxLogsProcessor: args.TxLogsProcessor, - BadTxForwarder: args.BadTxForwarder, - EnableRoundsHandler: args.EnableRoundsHandler, - EnableEpochsHandler: args.EnableEpochsHandler, - EnableEpochs: args.EnableEpochs, - VMOutputCacher: args.VMOutputCacher, - WasmVMChangeLocker: args.WasmVMChangeLocker, - IsGenesisProcessing: args.IsGenesisProcessing, - FailedTxLogsAccumulator: args.FailedTxLogsAccumulator, + VmContainer: args.VmContainer, + ArgsParser: args.ArgsParser, + Hasher: args.Hasher, + Marshalizer: args.Marshalizer, + AccountsDB: args.AccountsDB, + BlockChainHook: args.BlockChainHook, + BuiltInFunctions: args.BuiltInFunctions, + PubkeyConv: args.PubkeyConv, + ShardCoordinator: args.ShardCoordinator, + ScrForwarder: args.ScrForwarder, + TxFeeHandler: args.TxFeeHandler, + EconomicsFee: args.EconomicsFee, + TxTypeHandler: args.TxTypeHandler, + GasHandler: args.GasHandler, + GasSchedule: args.GasSchedule, + TxLogsProcessor: args.TxLogsProcessor, + BadTxForwarder: args.BadTxForwarder, + EnableRoundsHandler: args.EnableRoundsHandler, + EnableEpochsHandler: args.EnableEpochsHandler, + EnableEpochs: args.EnableEpochs, + VMOutputCacher: args.VMOutputCacher, + WasmVMChangeLocker: args.WasmVMChangeLocker, + IsGenesisProcessing: args.IsGenesisProcessing, }, } if check.IfNil(epochNotifier) { diff --git a/process/smartContract/processProxy/processProxy_test.go b/process/smartContract/processProxy/processProxy_test.go index 98a56fd0f30..d153615600f 100644 --- a/process/smartContract/processProxy/processProxy_test.go +++ b/process/smartContract/processProxy/processProxy_test.go @@ -23,7 +23,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" epochNotifierMock "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/multiversx/mx-chain-vm-common-go/builtInFunctions" @@ -77,10 +76,9 @@ func createMockSmartContractProcessorArguments() scrCommon.ArgsNewSmartContractP return flag == common.SCDeployFlag }, }, - EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, - WasmVMChangeLocker: &sync.RWMutex{}, - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, + WasmVMChangeLocker: &sync.RWMutex{}, + VMOutputCacher: txcache.NewDisabledCache(), } } diff --git a/process/smartContract/processProxy/testProcessProxy.go b/process/smartContract/processProxy/testProcessProxy.go index 65e5d525565..5d5d96ee0d2 100644 --- a/process/smartContract/processProxy/testProcessProxy.go +++ b/process/smartContract/processProxy/testProcessProxy.go @@ -28,30 +28,29 @@ type scProcessorTestProxy struct { func NewTestSmartContractProcessorProxy(args scrCommon.ArgsNewSmartContractProcessor, epochNotifier vmcommon.EpochNotifier) (*scProcessorTestProxy, error) { scProcessorTestProxy := &scProcessorTestProxy{ args: scrCommon.ArgsNewSmartContractProcessor{ - VmContainer: args.VmContainer, - ArgsParser: args.ArgsParser, - Hasher: args.Hasher, - Marshalizer: args.Marshalizer, - AccountsDB: args.AccountsDB, - BlockChainHook: args.BlockChainHook, - BuiltInFunctions: args.BuiltInFunctions, - PubkeyConv: args.PubkeyConv, - ShardCoordinator: args.ShardCoordinator, - ScrForwarder: args.ScrForwarder, - TxFeeHandler: args.TxFeeHandler, - EconomicsFee: args.EconomicsFee, - TxTypeHandler: args.TxTypeHandler, - GasHandler: args.GasHandler, - GasSchedule: args.GasSchedule, - TxLogsProcessor: args.TxLogsProcessor, - BadTxForwarder: args.BadTxForwarder, - EnableRoundsHandler: args.EnableRoundsHandler, - EnableEpochsHandler: args.EnableEpochsHandler, - EnableEpochs: args.EnableEpochs, - VMOutputCacher: args.VMOutputCacher, - WasmVMChangeLocker: args.WasmVMChangeLocker, - IsGenesisProcessing: args.IsGenesisProcessing, - FailedTxLogsAccumulator: args.FailedTxLogsAccumulator, + VmContainer: args.VmContainer, + ArgsParser: args.ArgsParser, + Hasher: args.Hasher, + Marshalizer: args.Marshalizer, + AccountsDB: args.AccountsDB, + BlockChainHook: args.BlockChainHook, + BuiltInFunctions: args.BuiltInFunctions, + PubkeyConv: args.PubkeyConv, + ShardCoordinator: args.ShardCoordinator, + ScrForwarder: args.ScrForwarder, + TxFeeHandler: args.TxFeeHandler, + EconomicsFee: args.EconomicsFee, + TxTypeHandler: args.TxTypeHandler, + GasHandler: args.GasHandler, + GasSchedule: args.GasSchedule, + TxLogsProcessor: args.TxLogsProcessor, + BadTxForwarder: args.BadTxForwarder, + EnableRoundsHandler: args.EnableRoundsHandler, + EnableEpochsHandler: args.EnableEpochsHandler, + EnableEpochs: args.EnableEpochs, + VMOutputCacher: args.VMOutputCacher, + WasmVMChangeLocker: args.WasmVMChangeLocker, + IsGenesisProcessing: args.IsGenesisProcessing, }, } diff --git a/process/smartContract/process_test.go b/process/smartContract/process_test.go index 29c1e082be3..bc8caf169f3 100644 --- a/process/smartContract/process_test.go +++ b/process/smartContract/process_test.go @@ -39,7 +39,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" "github.com/multiversx/mx-chain-go/testscommon/trie" "github.com/multiversx/mx-chain-go/testscommon/vmcommonMocks" @@ -116,12 +115,11 @@ func createMockSmartContractProcessorArguments() scrCommon.ArgsNewSmartContractP GasHandler: &testscommon.GasHandlerStub{ SetGasRefundedCalled: func(gasRefunded uint64, hash []byte) {}, }, - GasSchedule: testscommon.NewGasScheduleNotifierMock(gasSchedule), - EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.SCDeployFlag), - WasmVMChangeLocker: &sync.RWMutex{}, - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + GasSchedule: testscommon.NewGasScheduleNotifierMock(gasSchedule), + EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.SCDeployFlag), + WasmVMChangeLocker: &sync.RWMutex{}, + VMOutputCacher: txcache.NewDisabledCache(), } } diff --git a/process/smartContract/processorV2/processV2.go b/process/smartContract/processorV2/processV2.go index dafa4f9712f..5f6c02b7d09 100644 --- a/process/smartContract/processorV2/processV2.go +++ b/process/smartContract/processorV2/processV2.go @@ -81,14 +81,13 @@ type scProcessor struct { txTypeHandler process.TxTypeHandler gasHandler process.GasHandler - builtInGasCosts map[string]uint64 - persistPerByte uint64 - storePerByte uint64 - mutGasLock sync.RWMutex - txLogsProcessor process.TransactionLogProcessor - failedTxLogsAccumulator process.FailedTxLogsAccumulator - vmOutputCacher storage.Cacher - isGenesisProcessing bool + builtInGasCosts map[string]uint64 + persistPerByte uint64 + storePerByte uint64 + mutGasLock sync.RWMutex + txLogsProcessor process.TransactionLogProcessor + vmOutputCacher storage.Cacher + isGenesisProcessing bool executableCheckers map[string]scrCommon.ExecutableChecker mutExecutableCheckers sync.RWMutex @@ -162,9 +161,6 @@ func NewSmartContractProcessorV2(args scrCommon.ArgsNewSmartContractProcessor) ( if check.IfNil(args.TxLogsProcessor) { return nil, process.ErrNilTxLogsProcessor } - if check.IfNil(args.FailedTxLogsAccumulator) { - return nil, process.ErrNilFailedTxLogsAccumulator - } if check.IfNil(args.EnableEpochsHandler) { return nil, process.ErrNilEnableEpochsHandler } @@ -188,31 +184,30 @@ func NewSmartContractProcessorV2(args scrCommon.ArgsNewSmartContractProcessor) ( builtInFuncCost := args.GasSchedule.LatestGasSchedule()[common.BuiltInCost] baseOperationCost := args.GasSchedule.LatestGasSchedule()[common.BaseOperationCost] sc := &scProcessor{ - vmContainer: args.VmContainer, - argsParser: args.ArgsParser, - hasher: args.Hasher, - marshalizer: args.Marshalizer, - accounts: args.AccountsDB, - blockChainHook: args.BlockChainHook, - pubkeyConv: args.PubkeyConv, - shardCoordinator: args.ShardCoordinator, - scrForwarder: args.ScrForwarder, - txFeeHandler: args.TxFeeHandler, - economicsFee: args.EconomicsFee, - txTypeHandler: args.TxTypeHandler, - gasHandler: args.GasHandler, - builtInGasCosts: builtInFuncCost, - txLogsProcessor: args.TxLogsProcessor, - failedTxLogsAccumulator: args.FailedTxLogsAccumulator, - badTxForwarder: args.BadTxForwarder, - builtInFunctions: args.BuiltInFunctions, - isGenesisProcessing: args.IsGenesisProcessing, - arwenChangeLocker: args.WasmVMChangeLocker, - vmOutputCacher: args.VMOutputCacher, - enableEpochsHandler: args.EnableEpochsHandler, - storePerByte: baseOperationCost["StorePerByte"], - persistPerByte: baseOperationCost["PersistPerByte"], - executableCheckers: scrCommon.CreateExecutableCheckersMap(args.BuiltInFunctions), + vmContainer: args.VmContainer, + argsParser: args.ArgsParser, + hasher: args.Hasher, + marshalizer: args.Marshalizer, + accounts: args.AccountsDB, + blockChainHook: args.BlockChainHook, + pubkeyConv: args.PubkeyConv, + shardCoordinator: args.ShardCoordinator, + scrForwarder: args.ScrForwarder, + txFeeHandler: args.TxFeeHandler, + economicsFee: args.EconomicsFee, + txTypeHandler: args.TxTypeHandler, + gasHandler: args.GasHandler, + builtInGasCosts: builtInFuncCost, + txLogsProcessor: args.TxLogsProcessor, + badTxForwarder: args.BadTxForwarder, + builtInFunctions: args.BuiltInFunctions, + isGenesisProcessing: args.IsGenesisProcessing, + arwenChangeLocker: args.WasmVMChangeLocker, + vmOutputCacher: args.VMOutputCacher, + enableEpochsHandler: args.EnableEpochsHandler, + storePerByte: baseOperationCost["StorePerByte"], + persistPerByte: baseOperationCost["PersistPerByte"], + executableCheckers: scrCommon.CreateExecutableCheckersMap(args.BuiltInFunctions), } sc.esdtTransferParser, err = parsers.NewESDTTransferParser(args.Marshalizer) @@ -1412,19 +1407,19 @@ func (sc *scProcessor) isCrossShardESDTTransfer(sender []byte, receiver []byte, func (sc *scProcessor) getOriginalTxHashIfIntraShardRelayedSCR( tx data.TransactionHandler, txHash []byte, -) ([]byte, bool) { +) []byte { relayedSCR, isRelayed := isRelayedTx(tx) if !isRelayed { - return txHash, isRelayed + return txHash } sndShardID := sc.shardCoordinator.ComputeId(relayedSCR.SndAddr) rcvShardID := sc.shardCoordinator.ComputeId(relayedSCR.RcvAddr) if sndShardID != rcvShardID { - return txHash, isRelayed + return txHash } - return relayedSCR.OriginalTxHash, isRelayed + return relayedSCR.OriginalTxHash } // ProcessIfError creates a smart contract result, consumes the gas and returns the value to the user @@ -1514,15 +1509,10 @@ func (sc *scProcessor) processIfErrorWithAddedLogs(acntSnd state.UserAccountHand processIfErrorLogs = append(processIfErrorLogs, failureContext.logs...) } - logsTxHash, isRelayed := sc.getOriginalTxHashIfIntraShardRelayedSCR(tx, failureContext.txHash) - var ignorableError error - if isRelayed { - ignorableError = sc.failedTxLogsAccumulator.SaveLogs(logsTxHash, tx, processIfErrorLogs) - } else { - ignorableError = sc.txLogsProcessor.SaveLog(logsTxHash, tx, processIfErrorLogs) - } + logsTxHash := sc.getOriginalTxHashIfIntraShardRelayedSCR(tx, failureContext.txHash) + ignorableError := sc.txLogsProcessor.SaveLog(logsTxHash, tx, processIfErrorLogs) if ignorableError != nil { - log.Debug("scProcessor.ProcessIfError() save log", "error", ignorableError.Error(), "isRelayed", isRelayed) + log.Debug("scProcessor.ProcessIfError() save log", "error", ignorableError.Error()) } txType, _ := sc.txTypeHandler.ComputeTransactionType(tx) diff --git a/process/smartContract/processorV2/process_test.go b/process/smartContract/processorV2/process_test.go index 8722991d0a7..905c18a033d 100644 --- a/process/smartContract/processorV2/process_test.go +++ b/process/smartContract/processorV2/process_test.go @@ -43,7 +43,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" testsCommonStorage "github.com/multiversx/mx-chain-go/testscommon/storage" "github.com/multiversx/mx-chain-go/testscommon/vmcommonMocks" @@ -131,10 +130,9 @@ func createMockSmartContractProcessorArguments() scrCommon.ArgsNewSmartContractP return flag == common.SCDeployFlag }, }, - GasSchedule: testscommon.NewGasScheduleNotifierMock(gasSchedule), - WasmVMChangeLocker: &sync.RWMutex{}, - VMOutputCacher: txcache.NewDisabledCache(), - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + GasSchedule: testscommon.NewGasScheduleNotifierMock(gasSchedule), + WasmVMChangeLocker: &sync.RWMutex{}, + VMOutputCacher: txcache.NewDisabledCache(), } } @@ -337,17 +335,6 @@ func TestNewSmartContractProcessor_NilTxLogsProcessorShouldErr(t *testing.T) { require.Equal(t, process.ErrNilTxLogsProcessor, err) } -func TestNewSmartContractProcessor_NilFailedTxLogsAccumulatorShouldErr(t *testing.T) { - t.Parallel() - - arguments := createMockSmartContractProcessorArguments() - arguments.FailedTxLogsAccumulator = nil - sc, err := NewSmartContractProcessorV2(arguments) - - require.Nil(t, sc) - require.Equal(t, process.ErrNilFailedTxLogsAccumulator, err) -} - func TestNewSmartContractProcessor_NilBadTxForwarderShouldErr(t *testing.T) { t.Parallel() @@ -3345,8 +3332,8 @@ func TestScProcessor_ProcessRelayedSCRValueBackToRelayer(t *testing.T) { }, } wasSaveLogsCalled := false - arguments.FailedTxLogsAccumulator = &processMocks.FailedTxLogsAccumulatorMock{ - SaveLogsCalled: func(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error { + arguments.TxLogsProcessor = &mock.TxLogsProcessorStub{ + SaveLogCalled: func(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error { wasSaveLogsCalled = true return nil }, @@ -4083,20 +4070,18 @@ func TestProcessGetOriginalTxHashForRelayedIntraShard(t *testing.T) { scr := &smartContractResult.SmartContractResult{Value: big.NewInt(1), SndAddr: bytes.Repeat([]byte{1}, 32)} scrHash := []byte("hash") - logHash, isRelayed := sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) + logHash := sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) assert.Equal(t, scrHash, logHash) - assert.False(t, isRelayed) scr.OriginalTxHash = []byte("originalHash") scr.RelayerAddr = bytes.Repeat([]byte{1}, 32) scr.SndAddr = bytes.Repeat([]byte{1}, 32) scr.RcvAddr = bytes.Repeat([]byte{1}, 32) - logHash, isRelayed = sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) + logHash = sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) assert.Equal(t, scr.OriginalTxHash, logHash) - assert.True(t, isRelayed) scr.RcvAddr = bytes.Repeat([]byte{2}, 32) - logHash, _ = sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) + logHash = sc.getOriginalTxHashIfIntraShardRelayedSCR(scr, scrHash) assert.Equal(t, scrHash, logHash) } diff --git a/process/smartContract/scrCommon/common.go b/process/smartContract/scrCommon/common.go index 07efc6cfd59..8cd8efd6484 100644 --- a/process/smartContract/scrCommon/common.go +++ b/process/smartContract/scrCommon/common.go @@ -32,30 +32,29 @@ type ExecutableChecker interface { // ArgsNewSmartContractProcessor defines the arguments needed for new smart contract processor type ArgsNewSmartContractProcessor struct { - VmContainer process.VirtualMachinesContainer - ArgsParser process.ArgumentsParser - Hasher hashing.Hasher - Marshalizer marshal.Marshalizer - AccountsDB state.AccountsAdapter - BlockChainHook process.BlockChainHookHandler - BuiltInFunctions vmcommon.BuiltInFunctionContainer - PubkeyConv core.PubkeyConverter - ShardCoordinator sharding.Coordinator - ScrForwarder process.IntermediateTransactionHandler - TxFeeHandler process.TransactionFeeHandler - EconomicsFee process.FeeHandler - TxTypeHandler process.TxTypeHandler - GasHandler process.GasHandler - GasSchedule core.GasScheduleNotifier - TxLogsProcessor process.TransactionLogProcessor - FailedTxLogsAccumulator process.FailedTxLogsAccumulator - BadTxForwarder process.IntermediateTransactionHandler - EnableRoundsHandler process.EnableRoundsHandler - EnableEpochsHandler common.EnableEpochsHandler - EnableEpochs config.EnableEpochs - VMOutputCacher storage.Cacher - WasmVMChangeLocker common.Locker - IsGenesisProcessing bool + VmContainer process.VirtualMachinesContainer + ArgsParser process.ArgumentsParser + Hasher hashing.Hasher + Marshalizer marshal.Marshalizer + AccountsDB state.AccountsAdapter + BlockChainHook process.BlockChainHookHandler + BuiltInFunctions vmcommon.BuiltInFunctionContainer + PubkeyConv core.PubkeyConverter + ShardCoordinator sharding.Coordinator + ScrForwarder process.IntermediateTransactionHandler + TxFeeHandler process.TransactionFeeHandler + EconomicsFee process.FeeHandler + TxTypeHandler process.TxTypeHandler + GasHandler process.GasHandler + GasSchedule core.GasScheduleNotifier + TxLogsProcessor process.TransactionLogProcessor + BadTxForwarder process.IntermediateTransactionHandler + EnableRoundsHandler process.EnableRoundsHandler + EnableEpochsHandler common.EnableEpochsHandler + EnableEpochs config.EnableEpochs + VMOutputCacher storage.Cacher + WasmVMChangeLocker common.Locker + IsGenesisProcessing bool } // FindVMByScAddress is exported for use in all version of scr processors diff --git a/process/transaction/export_test.go b/process/transaction/export_test.go index ef23d5c114f..cd657c3991d 100644 --- a/process/transaction/export_test.go +++ b/process/transaction/export_test.go @@ -62,8 +62,7 @@ func (txProc *txProcessor) ProcessUserTx( userTx, relayedTxValue, relayedNonce, - originalTxHash, - nonRelayedV3UserTxIdx) + originalTxHash) } // ProcessMoveBalanceCostRelayedUserTx calls the un-exported method processMoveBalanceCostRelayedUserTx @@ -93,8 +92,7 @@ func (txProc *txProcessor) ExecuteFailedRelayedTransaction( relayedNonce, originalTx, originalTxHash, - errorMsg, - nonRelayedV3UserTxIdx) + errorMsg) } // CheckMaxGasPrice calls the un-exported method checkMaxGasPrice diff --git a/process/transaction/interceptedTransaction.go b/process/transaction/interceptedTransaction.go index 831afdcbcbc..75b9a65ae7c 100644 --- a/process/transaction/interceptedTransaction.go +++ b/process/transaction/interceptedTransaction.go @@ -13,7 +13,6 @@ import ( "github.com/multiversx/mx-chain-core-go/hashing" "github.com/multiversx/mx-chain-core-go/marshal" "github.com/multiversx/mx-chain-crypto-go" - "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/sharding" logger "github.com/multiversx/mx-chain-logger-go" @@ -43,8 +42,6 @@ type InterceptedTransaction struct { sndShard uint32 isForCurrentShard bool enableSignedTxWithHash bool - enableEpochsHandler common.EnableEpochsHandler - relayedTxV3Processor process.RelayedTxV3Processor } // NewInterceptedTransaction returns a new instance of InterceptedTransaction @@ -64,8 +61,6 @@ func NewInterceptedTransaction( enableSignedTxWithHash bool, txSignHasher hashing.Hasher, txVersionChecker process.TxVersionCheckerHandler, - enableEpochsHandler common.EnableEpochsHandler, - relayedTxV3Processor process.RelayedTxV3Processor, ) (*InterceptedTransaction, error) { if txBuff == nil { @@ -110,12 +105,6 @@ func NewInterceptedTransaction( if check.IfNil(txVersionChecker) { return nil, process.ErrNilTransactionVersionChecker } - if check.IfNil(enableEpochsHandler) { - return nil, process.ErrNilEnableEpochsHandler - } - if check.IfNil(relayedTxV3Processor) { - return nil, process.ErrNilRelayedTxV3Processor - } tx, err := createTx(protoMarshalizer, txBuff) if err != nil { @@ -138,8 +127,6 @@ func NewInterceptedTransaction( enableSignedTxWithHash: enableSignedTxWithHash, txVersionChecker: txVersionChecker, txSignHasher: txSignHasher, - enableEpochsHandler: enableEpochsHandler, - relayedTxV3Processor: relayedTxV3Processor, } err = inTx.processFields(txBuff) @@ -212,26 +199,13 @@ func (inTx *InterceptedTransaction) CheckValidity() error { return err } - err = inTx.verifyIfRelayedTxV3(inTx.tx) - if err != nil { - return err - } - - if len(inTx.tx.RelayerAddr) > 0 { - return fmt.Errorf("%w, relayer address found on transaction", process.ErrWrongTransaction) - } - inTx.whiteListerVerifiedTxs.Add([][]byte{inTx.Hash()}) } return nil } -func (inTx *InterceptedTransaction) checkRecursiveRelayed(userTxData []byte, innerTxs []*transaction.Transaction) error { - if isRelayedV3(innerTxs) { - return process.ErrRecursiveRelayedTxIsNotAllowed - } - +func (inTx *InterceptedTransaction) checkRecursiveRelayed(userTxData []byte) error { funcName, _, err := inTx.argsParser.ParseCallData(string(userTxData)) if err != nil { return nil @@ -249,46 +223,6 @@ func isRelayedTx(funcName string) bool { core.RelayedTransactionV2 == funcName } -func isRelayedV3(innerTxs []*transaction.Transaction) bool { - return len(innerTxs) > 0 -} - -func (inTx *InterceptedTransaction) verifyIfRelayedTxV3(tx *transaction.Transaction) error { - if len(tx.InnerTransactions) == 0 { - return nil - } - if !inTx.enableEpochsHandler.IsFlagEnabled(common.RelayedTransactionsV3Flag) { - return process.ErrRelayedTxV3Disabled - } - err := inTx.relayedTxV3Processor.CheckRelayedTx(tx) - if err != nil { - return err - } - - funcName, _, err := inTx.argsParser.ParseCallData(string(tx.Data)) - if err == nil && isRelayedTx(funcName) { - return process.ErrMultipleRelayedTxTypesIsNotAllowed - } - - return inTx.verifyInnerTransactions(tx) -} - -func (inTx *InterceptedTransaction) verifyInnerTransactions(tx *transaction.Transaction) error { - for _, innerTx := range tx.InnerTransactions { - err := inTx.integrity(innerTx) - if err != nil { - return fmt.Errorf("inner transaction: %w", err) - } - - err = inTx.verifyUserTx(innerTx) - if err != nil { - return fmt.Errorf("inner transaction: %w", err) - } - } - - return nil -} - func (inTx *InterceptedTransaction) verifyIfRelayedTxV2(tx *transaction.Transaction) error { funcName, userTxArgs, err := inTx.argsParser.ParseCallData(string(tx.Data)) if err != nil { @@ -298,10 +232,6 @@ func (inTx *InterceptedTransaction) verifyIfRelayedTxV2(tx *transaction.Transact return nil } - if len(tx.InnerTransactions) > 0 { - return process.ErrMultipleRelayedTxTypesIsNotAllowed - } - userTx, err := createRelayedV2(tx, userTxArgs) if err != nil { return err @@ -323,10 +253,6 @@ func (inTx *InterceptedTransaction) verifyIfRelayedTx(tx *transaction.Transactio return process.ErrInvalidArguments } - if len(tx.InnerTransactions) > 0 { - return process.ErrMultipleRelayedTxTypesIsNotAllowed - } - userTx, err := createTx(inTx.signMarshalizer, userTxArgs[0]) if err != nil { return fmt.Errorf("inner transaction: %w", err) @@ -346,7 +272,7 @@ func (inTx *InterceptedTransaction) verifyIfRelayedTx(tx *transaction.Transactio func (inTx *InterceptedTransaction) verifyUserTx(userTx *transaction.Transaction) error { // recursive relayed transactions are not allowed - err := inTx.checkRecursiveRelayed(userTx.Data, userTx.InnerTransactions) + err := inTx.checkRecursiveRelayed(userTx.Data) if err != nil { return fmt.Errorf("inner transaction: %w", err) } @@ -537,11 +463,6 @@ func (inTx *InterceptedTransaction) Fee() *big.Int { return inTx.feeHandler.ComputeTxFee(inTx.tx) } -// RelayerAddress returns the relayer address from transaction -func (inTx *InterceptedTransaction) RelayerAddress() []byte { - return inTx.tx.RelayerAddr -} - // Type returns the type of this intercepted data func (inTx *InterceptedTransaction) Type() string { return "intercepted tx" diff --git a/process/transaction/interceptedTransaction_test.go b/process/transaction/interceptedTransaction_test.go index 44d416194ab..f35ce467d13 100644 --- a/process/transaction/interceptedTransaction_test.go +++ b/process/transaction/interceptedTransaction_test.go @@ -15,7 +15,6 @@ import ( "github.com/multiversx/mx-chain-core-go/data" dataTransaction "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-crypto-go" - "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/process/interceptors" "github.com/multiversx/mx-chain-go/process/mock" @@ -23,10 +22,8 @@ import ( "github.com/multiversx/mx-chain-go/process/transaction" "github.com/multiversx/mx-chain-go/testscommon" "github.com/multiversx/mx-chain-go/testscommon/economicsmocks" - "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" logger "github.com/multiversx/mx-chain-logger-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -37,10 +34,8 @@ var errSignerMockVerifySigFails = errors.New("errSignerMockVerifySigFails") var senderShard = uint32(2) var recvShard = uint32(3) -var relayerShard = senderShard var senderAddress = []byte("12345678901234567890123456789012") var recvAddress = []byte("23456789012345678901234567890123") -var relayerAddress = []byte("34567890123456789012345678901234") var sigBad = []byte("bad-signature") var sigOk = []byte("signature") @@ -95,9 +90,6 @@ func createInterceptedTxWithTxFeeHandlerAndVersionChecker(tx *dataTransaction.Tr if bytes.Equal(address, recvAddress) { return recvShard } - if bytes.Equal(address, relayerAddress) { - return relayerShard - } return shardCoordinator.CurrentShard } @@ -122,8 +114,6 @@ func createInterceptedTxWithTxFeeHandlerAndVersionChecker(tx *dataTransaction.Tr false, &hashingMocks.HasherMock{}, txVerChecker, - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) } @@ -143,9 +133,6 @@ func createInterceptedTxFromPlainTx(tx *dataTransaction.Transaction, txFeeHandle if bytes.Equal(address, recvAddress) { return recvShard } - if bytes.Equal(address, relayerAddress) { - return relayerShard - } return shardCoordinator.CurrentShard } @@ -170,8 +157,6 @@ func createInterceptedTxFromPlainTx(tx *dataTransaction.Transaction, txFeeHandle false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(minTxVersion), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) } @@ -191,23 +176,10 @@ func createInterceptedTxFromPlainTxWithArgParser(tx *dataTransaction.Transaction if bytes.Equal(address, recvAddress) { return recvShard } - if bytes.Equal(address, relayerAddress) { - return relayerShard - } return shardCoordinator.CurrentShard } - txFeeHandler := createFreeTxFeeHandler() - relayedTxV3Processor, err := transaction.NewRelayedTxV3Processor(transaction.ArgRelayedTxV3Processor{ - EconomicsFee: txFeeHandler, - ShardCoordinator: shardCoordinator, - MaxTransactionsAllowed: 10, - }) - if err != nil { - return nil, err - } - return transaction.NewInterceptedTransaction( txBuff, marshalizer, @@ -221,15 +193,13 @@ func createInterceptedTxFromPlainTxWithArgParser(tx *dataTransaction.Transaction }, }, shardCoordinator, - txFeeHandler, + createFreeTxFeeHandler(), &testscommon.WhiteListHandlerStub{}, smartContract.NewArgumentParser(), tx.ChainID, false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(tx.Version), - enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.RelayedTransactionsV3Flag), - relayedTxV3Processor, ) } @@ -254,8 +224,6 @@ func TestNewInterceptedTransaction_NilBufferShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -281,8 +249,6 @@ func TestNewInterceptedTransaction_NilArgsParser(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -308,8 +274,6 @@ func TestNewInterceptedTransaction_NilVersionChecker(t *testing.T) { false, &hashingMocks.HasherMock{}, nil, - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -335,8 +299,6 @@ func TestNewInterceptedTransaction_NilMarshalizerShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -362,8 +324,6 @@ func TestNewInterceptedTransaction_NilSignMarshalizerShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -389,8 +349,6 @@ func TestNewInterceptedTransaction_NilHasherShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -416,8 +374,6 @@ func TestNewInterceptedTransaction_NilKeyGenShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -443,8 +399,6 @@ func TestNewInterceptedTransaction_NilSignerShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -470,8 +424,6 @@ func TestNewInterceptedTransaction_NilPubkeyConverterShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -497,8 +449,6 @@ func TestNewInterceptedTransaction_NilCoordinatorShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -524,8 +474,6 @@ func TestNewInterceptedTransaction_NilFeeHandlerShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -551,8 +499,6 @@ func TestNewInterceptedTransaction_NilWhiteListerVerifiedTxsShouldErr(t *testing false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -578,8 +524,6 @@ func TestNewInterceptedTransaction_InvalidChainIDShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -605,68 +549,12 @@ func TestNewInterceptedTransaction_NilTxSignHasherShouldErr(t *testing.T) { false, nil, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) assert.Equal(t, process.ErrNilHasher, err) } -func TestNewInterceptedTransaction_NilEnableEpochsHandlerShouldErr(t *testing.T) { - t.Parallel() - - txi, err := transaction.NewInterceptedTransaction( - make([]byte, 0), - &mock.MarshalizerMock{}, - &mock.MarshalizerMock{}, - &hashingMocks.HasherMock{}, - &mock.SingleSignKeyGenMock{}, - &mock.SignerMock{}, - createMockPubKeyConverter(), - mock.NewOneShardCoordinatorMock(), - &economicsmocks.EconomicsHandlerStub{}, - &testscommon.WhiteListHandlerStub{}, - &testscommon.ArgumentParserMock{}, - []byte("chainID"), - false, - &hashingMocks.HasherMock{}, - versioning.NewTxVersionChecker(1), - nil, - &processMocks.RelayedTxV3ProcessorMock{}, - ) - - assert.Nil(t, txi) - assert.Equal(t, process.ErrNilEnableEpochsHandler, err) -} - -func TestNewInterceptedTransaction_NilRelayedV3ProcessorShouldErr(t *testing.T) { - t.Parallel() - - txi, err := transaction.NewInterceptedTransaction( - make([]byte, 0), - &mock.MarshalizerMock{}, - &mock.MarshalizerMock{}, - &hashingMocks.HasherMock{}, - &mock.SingleSignKeyGenMock{}, - &mock.SignerMock{}, - createMockPubKeyConverter(), - mock.NewOneShardCoordinatorMock(), - &economicsmocks.EconomicsHandlerStub{}, - &testscommon.WhiteListHandlerStub{}, - &testscommon.ArgumentParserMock{}, - []byte("chainID"), - false, - &hashingMocks.HasherMock{}, - versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - nil, - ) - - assert.Nil(t, txi) - assert.Equal(t, process.ErrNilRelayedTxV3Processor, err) -} - func TestNewInterceptedTransaction_UnmarshalingTxFailsShouldErr(t *testing.T) { t.Parallel() @@ -692,8 +580,6 @@ func TestNewInterceptedTransaction_UnmarshalingTxFailsShouldErr(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(1), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, txi) @@ -1110,32 +996,6 @@ func TestInterceptedTransaction_CheckValidityOkValsShouldWork(t *testing.T) { assert.Nil(t, err) } -func TestInterceptedTransaction_CheckValidityRelayerAddressShouldError(t *testing.T) { - t.Parallel() - - minTxVersion := uint32(1) - chainID := []byte("chain") - tx := &dataTransaction.Transaction{ - Nonce: 1, - Value: big.NewInt(2), - Data: []byte("data"), - GasLimit: 3, - GasPrice: 4, - RcvAddr: recvAddress, - SndAddr: senderAddress, - Signature: sigOk, - ChainID: chainID, - Version: minTxVersion, - RelayerAddr: []byte("45678901234567890123456789012345"), - } - txi, _ := createInterceptedTxFromPlainTx(tx, createFreeTxFeeHandler(), chainID, minTxVersion) - - err := txi.CheckValidity() - - assert.True(t, errors.Is(err, process.ErrWrongTransaction)) - assert.True(t, strings.Contains(err.Error(), "relayer address found on transaction")) -} - func TestInterceptedTransaction_CheckValiditySignedWithHashButNotEnabled(t *testing.T) { t.Parallel() @@ -1190,8 +1050,6 @@ func TestInterceptedTransaction_CheckValiditySignedWithHashButNotEnabled(t *test false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(minTxVersion), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) err := txi.CheckValidity() @@ -1252,8 +1110,6 @@ func TestInterceptedTransaction_CheckValiditySignedWithHashShouldWork(t *testing true, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(minTxVersion), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) err := txi.CheckValidity() @@ -1339,8 +1195,6 @@ func TestInterceptedTransaction_ScTxDeployRecvShardIdShouldBeSendersShardId(t *t false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(minTxVersion), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Nil(t, err) @@ -1421,31 +1275,6 @@ func TestInterceptedTransaction_GetSenderAddress(t *testing.T) { assert.NotNil(t, result) } -func TestInterceptedTransaction_GetRelayerAddress(t *testing.T) { - t.Parallel() - - relayerAddr := []byte("34567890123456789012345678901234") - minTxVersion := uint32(1) - chainID := []byte("chain") - tx := &dataTransaction.Transaction{ - Nonce: 0, - Value: big.NewInt(2), - Data: []byte("data"), - GasLimit: 3, - GasPrice: 4, - RcvAddr: recvAddress, - SndAddr: senderAddress, - Signature: sigOk, - ChainID: chainID, - Version: minTxVersion, - RelayerAddr: relayerAddr, - } - - txi, _ := createInterceptedTxFromPlainTx(tx, createFreeTxFeeHandler(), chainID, minTxVersion) - result := txi.RelayerAddress() - assert.Equal(t, relayerAddr, result) -} - func TestInterceptedTransaction_CheckValiditySecondTimeDoesNotVerifySig(t *testing.T) { t.Parallel() @@ -1505,8 +1334,6 @@ func TestInterceptedTransaction_CheckValiditySecondTimeDoesNotVerifySig(t *testi false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(minTxVersion), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) require.Nil(t, err) @@ -1602,14 +1429,6 @@ func TestInterceptedTransaction_CheckValidityOfRelayedTx(t *testing.T) { err = txi.CheckValidity() assert.True(t, strings.Contains(err.Error(), process.ErrRecursiveRelayedTxIsNotAllowed.Error())) assert.Contains(t, err.Error(), "inner transaction") - - userTx.Data = []byte("") - userTxData, _ = marshalizer.Marshal(userTx) - tx.Data = []byte(core.RelayedTransaction + "@" + hex.EncodeToString(userTxData)) - tx.InnerTransactions = []*dataTransaction.Transaction{{Nonce: 100}} - txi, _ = createInterceptedTxFromPlainTxWithArgParser(tx) - err = txi.CheckValidity() - assert.True(t, strings.Contains(err.Error(), process.ErrMultipleRelayedTxTypesIsNotAllowed.Error())) } func TestInterceptedTransaction_CheckValidityOfRelayedTxV2(t *testing.T) { @@ -1673,16 +1492,6 @@ func TestInterceptedTransaction_CheckValidityOfRelayedTxV2(t *testing.T) { assert.True(t, strings.Contains(err.Error(), process.ErrRecursiveRelayedTxIsNotAllowed.Error())) assert.Contains(t, err.Error(), "inner transaction") - userTx.Data = []byte("") - marshalizer := &mock.MarshalizerMock{} - userTxData, _ := marshalizer.Marshal(userTx) - tx.Data = []byte(core.RelayedTransactionV2 + "@" + hex.EncodeToString(userTxData)) - tx.InnerTransactions = []*dataTransaction.Transaction{{Nonce: 100}} - txi, _ = createInterceptedTxFromPlainTxWithArgParser(tx) - err = txi.CheckValidity() - assert.True(t, strings.Contains(err.Error(), process.ErrMultipleRelayedTxTypesIsNotAllowed.Error())) - - tx.InnerTransactions = nil userTx.Signature = sigOk userTx.SndAddr = []byte("otherAddress") tx.Data = []byte(core.RelayedTransactionV2 + "@" + hex.EncodeToString(userTx.RcvAddr) + "@" + hex.EncodeToString(big.NewInt(0).SetUint64(userTx.Nonce).Bytes()) + "@" + hex.EncodeToString(userTx.Data) + "@" + hex.EncodeToString(userTx.Signature)) @@ -1691,177 +1500,6 @@ func TestInterceptedTransaction_CheckValidityOfRelayedTxV2(t *testing.T) { assert.Nil(t, err) } -func TestInterceptedTransaction_CheckValidityOfRelayedTxV3(t *testing.T) { - t.Parallel() - - minTxVersion := uint32(1) - chainID := []byte("chain") - innerTx := &dataTransaction.Transaction{ - Nonce: 1, - Value: big.NewInt(2), - Data: []byte("data inner tx 1"), - GasLimit: 3, - GasPrice: 4, - RcvAddr: recvAddress, - SndAddr: senderAddress, - Signature: sigOk, - ChainID: chainID, - Version: minTxVersion, - RelayerAddr: relayerAddress, - } - - tx := &dataTransaction.Transaction{ - Nonce: 1, - Value: big.NewInt(0), - GasLimit: 10, - GasPrice: 4, - RcvAddr: relayerAddress, - SndAddr: relayerAddress, - Signature: sigOk, - ChainID: chainID, - Version: minTxVersion, - InnerTransactions: []*dataTransaction.Transaction{innerTx}, - } - - t.Run("should work", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.Nil(t, err) - }) - t.Run("inner txs on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - innerTxCopy.InnerTransactions = []*dataTransaction.Transaction{{}} - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.Equal(t, process.ErrRecursiveRelayedTxIsNotAllowed, err) - }) - t.Run("different relayer on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - innerTxCopy.RelayerAddr = recvAddress - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.Equal(t, process.ErrRelayedTxV3RelayerMismatch, err) - }) - t.Run("different sender than receiver should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - txCopy.RcvAddr = recvAddress - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.Equal(t, process.ErrRelayedTxV3SenderDoesNotMatchReceiver, err) - }) - t.Run("empty signature on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - innerTxCopy.Signature = nil - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.NotNil(t, err) - }) - t.Run("bad signature on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - innerTxCopy.Signature = sigBad - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.NotNil(t, err) - }) - t.Run("inner tx on inner tx(recursive) should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - innerTx2 := &dataTransaction.Transaction{ - Nonce: 2, - Value: big.NewInt(3), - Data: []byte(""), - GasLimit: 3, - GasPrice: 4, - RcvAddr: recvAddress, - SndAddr: senderAddress, - Signature: sigOk, - ChainID: chainID, - Version: minTxVersion, - } - innerTxCopy.InnerTransactions = []*dataTransaction.Transaction{innerTx2} - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.NotNil(t, err) - }) - t.Run("relayed v3 not enabled yet should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - marshalizer := &mock.MarshalizerMock{} - txBuff, _ := marshalizer.Marshal(&txCopy) - txi, _ := transaction.NewInterceptedTransaction( - txBuff, - marshalizer, - marshalizer, - &hashingMocks.HasherMock{}, - createKeyGenMock(), - createDummySigner(), - &testscommon.PubkeyConverterStub{ - LenCalled: func() int { - return 32 - }, - }, - mock.NewMultipleShardsCoordinatorMock(), - createFreeTxFeeHandler(), - &testscommon.WhiteListHandlerStub{}, - &testscommon.ArgumentParserMock{}, - txCopy.ChainID, - false, - &hashingMocks.HasherMock{}, - versioning.NewTxVersionChecker(0), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, - ) - - assert.NotNil(t, txi) - err := txi.CheckValidity() - assert.Equal(t, process.ErrRelayedTxV3Disabled, err) - }) - t.Run("inner txs + relayed v2 should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - innerTxCopy := *innerTx - txCopy.InnerTransactions = []*dataTransaction.Transaction{&innerTxCopy} - marshaller := &marshallerMock.MarshalizerMock{} - userTxData, _ := marshaller.Marshal(innerTxCopy) - txCopy.Data = []byte(core.RelayedTransaction + "@" + hex.EncodeToString(userTxData)) - txi, _ := createInterceptedTxFromPlainTxWithArgParser(&txCopy) - err := txi.CheckValidity() - assert.Equal(t, process.ErrMultipleRelayedTxTypesIsNotAllowed, err) - }) -} - // ------- IsInterfaceNil func TestInterceptedTransaction_IsInterfaceNil(t *testing.T) { t.Parallel() @@ -1991,8 +1629,6 @@ func TestInterceptedTransaction_Fee(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(0), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) assert.Equal(t, big.NewInt(0), txin.Fee()) @@ -2036,8 +1672,6 @@ func TestInterceptedTransaction_String(t *testing.T) { false, &hashingMocks.HasherMock{}, versioning.NewTxVersionChecker(0), - &enableEpochsHandlerMock.EnableEpochsHandlerStub{}, - &processMocks.RelayedTxV3ProcessorMock{}, ) expectedFormat := fmt.Sprintf( diff --git a/process/transaction/relayedTxV3Processor.go b/process/transaction/relayedTxV3Processor.go deleted file mode 100644 index 1c25ad46214..00000000000 --- a/process/transaction/relayedTxV3Processor.go +++ /dev/null @@ -1,112 +0,0 @@ -package transaction - -import ( - "bytes" - "fmt" - "math/big" - - "github.com/multiversx/mx-chain-core-go/core/check" - "github.com/multiversx/mx-chain-core-go/data/transaction" - "github.com/multiversx/mx-chain-go/process" - "github.com/multiversx/mx-chain-go/sharding" -) - -const minTransactionsAllowed = 1 - -// ArgRelayedTxV3Processor is the DTO used to create a new instance of relayedTxV3Processor -type ArgRelayedTxV3Processor struct { - EconomicsFee process.FeeHandler - ShardCoordinator sharding.Coordinator - MaxTransactionsAllowed int -} - -type relayedTxV3Processor struct { - economicsFee process.FeeHandler - shardCoordinator sharding.Coordinator - maxTransactionsAllowed int -} - -// NewRelayedTxV3Processor returns a new instance of relayedTxV3Processor -func NewRelayedTxV3Processor(args ArgRelayedTxV3Processor) (*relayedTxV3Processor, error) { - err := checkArgs(args) - if err != nil { - return nil, err - } - return &relayedTxV3Processor{ - economicsFee: args.EconomicsFee, - shardCoordinator: args.ShardCoordinator, - maxTransactionsAllowed: args.MaxTransactionsAllowed, - }, nil -} - -func checkArgs(args ArgRelayedTxV3Processor) error { - if check.IfNil(args.EconomicsFee) { - return process.ErrNilEconomicsFeeHandler - } - if check.IfNil(args.ShardCoordinator) { - return process.ErrNilShardCoordinator - } - if args.MaxTransactionsAllowed < minTransactionsAllowed { - return fmt.Errorf("%w for MaxTransactionsAllowed, provided %d, min expected %d", process.ErrInvalidValue, args.MaxTransactionsAllowed, minTransactionsAllowed) - } - - return nil -} - -// CheckRelayedTx checks the relayed transaction and its inner transactions -func (proc *relayedTxV3Processor) CheckRelayedTx(tx *transaction.Transaction) error { - if len(tx.InnerTransactions) > proc.maxTransactionsAllowed { - return process.ErrRelayedTxV3TooManyInnerTransactions - } - if tx.GetValue().Cmp(big.NewInt(0)) != 0 { - return process.ErrRelayedTxV3ZeroVal - } - if !bytes.Equal(tx.RcvAddr, tx.SndAddr) { - return process.ErrRelayedTxV3SenderDoesNotMatchReceiver - } - if tx.GasLimit < proc.computeRelayedTxMinGasLimit(tx) { - return process.ErrRelayedTxV3GasLimitMismatch - } - if len(tx.Data) > 0 { - return process.ErrRelayedTxV3InvalidDataField - } - - innerTxs := tx.InnerTransactions - for _, innerTx := range innerTxs { - if !bytes.Equal(innerTx.RelayerAddr, tx.SndAddr) { - return process.ErrRelayedTxV3RelayerMismatch - } - if tx.GasPrice != innerTx.GasPrice { - return process.ErrRelayedV3GasPriceMismatch - } - if len(innerTx.InnerTransactions) > 0 { - return process.ErrRecursiveRelayedTxIsNotAllowed - } - - senderShard := proc.shardCoordinator.ComputeId(innerTx.SndAddr) - relayerShard := proc.shardCoordinator.ComputeId(innerTx.RelayerAddr) - if senderShard != relayerShard { - return process.ErrRelayedTxV3SenderShardMismatch - } - } - - return nil -} - -func (proc *relayedTxV3Processor) computeRelayedTxMinGasLimit(tx *transaction.Transaction) uint64 { - relayedTxGasLimit := proc.economicsFee.ComputeGasLimit(tx) - relayedTxMinGasLimit := proc.economicsFee.MinGasLimit() - relayedTxGasLimitDiff := relayedTxGasLimit - relayedTxMinGasLimit // this may be positive if the relayed tx is guarded - - totalGasLimit := relayedTxGasLimitDiff + relayedTxMinGasLimit*uint64(len(tx.InnerTransactions)) - for _, innerTx := range tx.InnerTransactions { - totalGasLimit += innerTx.GasLimit - } - - return totalGasLimit -} - -// IsInterfaceNil returns true if there is no value under the interface -func (proc *relayedTxV3Processor) IsInterfaceNil() bool { - return proc == nil -} diff --git a/process/transaction/relayedTxV3Processor_test.go b/process/transaction/relayedTxV3Processor_test.go deleted file mode 100644 index 7f6495ebd92..00000000000 --- a/process/transaction/relayedTxV3Processor_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package transaction_test - -import ( - "bytes" - "errors" - "math/big" - "strings" - "testing" - - "github.com/multiversx/mx-chain-core-go/data" - coreTransaction "github.com/multiversx/mx-chain-core-go/data/transaction" - "github.com/multiversx/mx-chain-go/process" - "github.com/multiversx/mx-chain-go/process/transaction" - "github.com/multiversx/mx-chain-go/testscommon" - "github.com/multiversx/mx-chain-go/testscommon/economicsmocks" - "github.com/stretchr/testify/require" -) - -const minGasLimit = uint64(1) - -func getDefaultTx() *coreTransaction.Transaction { - return &coreTransaction.Transaction{ - Nonce: 0, - Value: big.NewInt(0), - RcvAddr: []byte("rel"), - SndAddr: []byte("rel"), - GasPrice: 1, - GasLimit: minGasLimit * 4, - InnerTransactions: []*coreTransaction.Transaction{ - { - Nonce: 0, - Value: big.NewInt(1), - RcvAddr: []byte("rcv1"), - SndAddr: []byte("snd1"), - GasPrice: 1, - GasLimit: minGasLimit, - RelayerAddr: []byte("rel"), - }, - { - Nonce: 0, - Value: big.NewInt(1), - RcvAddr: []byte("rcv1"), - SndAddr: []byte("snd2"), - GasPrice: 1, - GasLimit: minGasLimit, - RelayerAddr: []byte("rel"), - }, - }, - } -} - -func createMockArgRelayedTxV3Processor() transaction.ArgRelayedTxV3Processor { - return transaction.ArgRelayedTxV3Processor{ - EconomicsFee: &economicsmocks.EconomicsHandlerStub{}, - ShardCoordinator: &testscommon.ShardsCoordinatorMock{}, - MaxTransactionsAllowed: 10, - } -} - -func TestNewRelayedTxV3Processor(t *testing.T) { - t.Parallel() - - t.Run("nil economics fee should error", func(t *testing.T) { - t.Parallel() - - args := createMockArgRelayedTxV3Processor() - args.EconomicsFee = nil - proc, err := transaction.NewRelayedTxV3Processor(args) - require.Nil(t, proc) - require.Equal(t, process.ErrNilEconomicsFeeHandler, err) - }) - t.Run("nil shard coordinator should error", func(t *testing.T) { - t.Parallel() - - args := createMockArgRelayedTxV3Processor() - args.ShardCoordinator = nil - proc, err := transaction.NewRelayedTxV3Processor(args) - require.Nil(t, proc) - require.Equal(t, process.ErrNilShardCoordinator, err) - }) - t.Run("invalid max transactions allowed should error", func(t *testing.T) { - t.Parallel() - - args := createMockArgRelayedTxV3Processor() - args.MaxTransactionsAllowed = 0 - proc, err := transaction.NewRelayedTxV3Processor(args) - require.Nil(t, proc) - require.True(t, errors.Is(err, process.ErrInvalidValue)) - require.True(t, strings.Contains(err.Error(), "MaxTransactionsAllowed")) - }) - t.Run("should work", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - require.NotNil(t, proc) - }) -} - -func TestRelayedTxV3Processor_IsInterfaceNil(t *testing.T) { - t.Parallel() - - args := createMockArgRelayedTxV3Processor() - args.EconomicsFee = nil - proc, _ := transaction.NewRelayedTxV3Processor(args) - require.True(t, proc.IsInterfaceNil()) - - proc, _ = transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.False(t, proc.IsInterfaceNil()) -} - -func TestRelayedTxV3Processor_CheckRelayedTx(t *testing.T) { - t.Parallel() - - t.Run("invalid num of inner txs should error", func(t *testing.T) { - t.Parallel() - - tx := getDefaultTx() - args := createMockArgRelayedTxV3Processor() - args.MaxTransactionsAllowed = len(tx.InnerTransactions) - 1 - proc, err := transaction.NewRelayedTxV3Processor(args) - require.NoError(t, err) - - tx.Value = big.NewInt(1) - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3TooManyInnerTransactions, err) - }) - t.Run("value on relayed tx should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.Value = big.NewInt(1) - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3ZeroVal, err) - }) - t.Run("relayed tx not to self should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.RcvAddr = []byte("another rcv") - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3SenderDoesNotMatchReceiver, err) - }) - t.Run("invalid gas limit should error", func(t *testing.T) { - t.Parallel() - - args := createMockArgRelayedTxV3Processor() - args.EconomicsFee = &economicsmocks.EconomicsHandlerStub{ - ComputeGasLimitCalled: func(tx data.TransactionWithFeeHandler) uint64 { - return minGasLimit - }, - } - proc, err := transaction.NewRelayedTxV3Processor(args) - require.NoError(t, err) - - tx := getDefaultTx() - tx.GasLimit = minGasLimit - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3GasLimitMismatch, err) - }) - t.Run("data field not empty should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.Data = []byte("dummy") - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3InvalidDataField, err) - }) - t.Run("inner txs on inner should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.InnerTransactions[0].InnerTransactions = []*coreTransaction.Transaction{{}} - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRecursiveRelayedTxIsNotAllowed, err) - }) - t.Run("relayer mismatch on inner should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.InnerTransactions[0].RelayerAddr = []byte("another relayer") - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3RelayerMismatch, err) - }) - t.Run("gas price mismatch on inner should error", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - tx.InnerTransactions[0].GasPrice = tx.GasPrice + 1 - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedV3GasPriceMismatch, err) - }) - t.Run("shard mismatch on inner should error", func(t *testing.T) { - t.Parallel() - - tx := getDefaultTx() - args := createMockArgRelayedTxV3Processor() - args.ShardCoordinator = &testscommon.ShardsCoordinatorMock{ - ComputeIdCalled: func(address []byte) uint32 { - if bytes.Equal(address, tx.SndAddr) { - return 0 - } - - return 1 - }, - } - proc, err := transaction.NewRelayedTxV3Processor(args) - require.NoError(t, err) - - err = proc.CheckRelayedTx(tx) - require.Equal(t, process.ErrRelayedTxV3SenderShardMismatch, err) - }) - t.Run("should work", func(t *testing.T) { - t.Parallel() - - proc, err := transaction.NewRelayedTxV3Processor(createMockArgRelayedTxV3Processor()) - require.NoError(t, err) - - tx := getDefaultTx() - err = proc.CheckRelayedTx(tx) - require.NoError(t, err) - }) -} diff --git a/process/transaction/shardProcess.go b/process/transaction/shardProcess.go index 6d2fbeb80f3..51910b537e2 100644 --- a/process/transaction/shardProcess.go +++ b/process/transaction/shardProcess.go @@ -31,8 +31,6 @@ var _ process.TransactionProcessor = (*txProcessor)(nil) // for move balance transactions that provide more gas than needed const RefundGasMessage = "refundedGas" -const nonRelayedV3UserTxIdx = -1 - type relayedFees struct { totalFee, remainingFee, relayerFee *big.Int } @@ -40,41 +38,37 @@ type relayedFees struct { // txProcessor implements TransactionProcessor interface and can modify account states according to a transaction type txProcessor struct { *baseTxProcessor - txFeeHandler process.TransactionFeeHandler - receiptForwarder process.IntermediateTransactionHandler - badTxForwarder process.IntermediateTransactionHandler - argsParser process.ArgumentsParser - scrForwarder process.IntermediateTransactionHandler - signMarshalizer marshal.Marshalizer - enableEpochsHandler common.EnableEpochsHandler - txLogsProcessor process.TransactionLogProcessor - relayedTxV3Processor process.RelayedTxV3Processor - failedTxLogsAccumulator process.FailedTxLogsAccumulator + txFeeHandler process.TransactionFeeHandler + receiptForwarder process.IntermediateTransactionHandler + badTxForwarder process.IntermediateTransactionHandler + argsParser process.ArgumentsParser + scrForwarder process.IntermediateTransactionHandler + signMarshalizer marshal.Marshalizer + enableEpochsHandler common.EnableEpochsHandler + txLogsProcessor process.TransactionLogProcessor } // ArgsNewTxProcessor defines the arguments needed for new tx processor type ArgsNewTxProcessor struct { - Accounts state.AccountsAdapter - Hasher hashing.Hasher - PubkeyConv core.PubkeyConverter - Marshalizer marshal.Marshalizer - SignMarshalizer marshal.Marshalizer - ShardCoordinator sharding.Coordinator - ScProcessor process.SmartContractProcessor - TxFeeHandler process.TransactionFeeHandler - TxTypeHandler process.TxTypeHandler - EconomicsFee process.FeeHandler - ReceiptForwarder process.IntermediateTransactionHandler - BadTxForwarder process.IntermediateTransactionHandler - ArgsParser process.ArgumentsParser - ScrForwarder process.IntermediateTransactionHandler - EnableRoundsHandler process.EnableRoundsHandler - EnableEpochsHandler common.EnableEpochsHandler - TxVersionChecker process.TxVersionCheckerHandler - GuardianChecker process.GuardianChecker - TxLogsProcessor process.TransactionLogProcessor - RelayedTxV3Processor process.RelayedTxV3Processor - FailedTxLogsAccumulator process.FailedTxLogsAccumulator + Accounts state.AccountsAdapter + Hasher hashing.Hasher + PubkeyConv core.PubkeyConverter + Marshalizer marshal.Marshalizer + SignMarshalizer marshal.Marshalizer + ShardCoordinator sharding.Coordinator + ScProcessor process.SmartContractProcessor + TxFeeHandler process.TransactionFeeHandler + TxTypeHandler process.TxTypeHandler + EconomicsFee process.FeeHandler + ReceiptForwarder process.IntermediateTransactionHandler + BadTxForwarder process.IntermediateTransactionHandler + ArgsParser process.ArgumentsParser + ScrForwarder process.IntermediateTransactionHandler + EnableRoundsHandler process.EnableRoundsHandler + EnableEpochsHandler common.EnableEpochsHandler + TxVersionChecker process.TxVersionCheckerHandler + GuardianChecker process.GuardianChecker + TxLogsProcessor process.TransactionLogProcessor } // NewTxProcessor creates a new txProcessor engine @@ -134,7 +128,6 @@ func NewTxProcessor(args ArgsNewTxProcessor) (*txProcessor, error) { common.RelayedTransactionsFlag, common.RelayedTransactionsV2Flag, common.RelayedNonceFixFlag, - common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag, }) if err != nil { @@ -149,12 +142,6 @@ func NewTxProcessor(args ArgsNewTxProcessor) (*txProcessor, error) { if check.IfNil(args.TxLogsProcessor) { return nil, process.ErrNilTxLogsProcessor } - if check.IfNil(args.RelayedTxV3Processor) { - return nil, process.ErrNilRelayedTxV3Processor - } - if check.IfNil(args.FailedTxLogsAccumulator) { - return nil, process.ErrNilFailedTxLogsAccumulator - } baseTxProcess := &baseTxProcessor{ accounts: args.Accounts, @@ -171,17 +158,15 @@ func NewTxProcessor(args ArgsNewTxProcessor) (*txProcessor, error) { } txProc := &txProcessor{ - baseTxProcessor: baseTxProcess, - txFeeHandler: args.TxFeeHandler, - receiptForwarder: args.ReceiptForwarder, - badTxForwarder: args.BadTxForwarder, - argsParser: args.ArgsParser, - scrForwarder: args.ScrForwarder, - signMarshalizer: args.SignMarshalizer, - enableEpochsHandler: args.EnableEpochsHandler, - txLogsProcessor: args.TxLogsProcessor, - relayedTxV3Processor: args.RelayedTxV3Processor, - failedTxLogsAccumulator: args.FailedTxLogsAccumulator, + baseTxProcessor: baseTxProcess, + txFeeHandler: args.TxFeeHandler, + receiptForwarder: args.ReceiptForwarder, + badTxForwarder: args.BadTxForwarder, + argsParser: args.ArgsParser, + scrForwarder: args.ScrForwarder, + signMarshalizer: args.SignMarshalizer, + enableEpochsHandler: args.EnableEpochsHandler, + txLogsProcessor: args.TxLogsProcessor, } return txProc, nil @@ -255,8 +240,6 @@ func (txProc *txProcessor) ProcessTransaction(tx *transaction.Transaction) (vmco return txProc.processRelayedTx(tx, acntSnd, acntDst) case process.RelayedTxV2: return txProc.processRelayedTxV2(tx, acntSnd, acntDst) - case process.RelayedTxV3: - return txProc.processRelayedTxV3(tx, acntSnd) } return vmcommon.UserError, txProc.executingFailedTransaction(tx, acntSnd, process.ErrWrongTransaction) @@ -621,7 +604,7 @@ func (txProc *txProcessor) finishExecutionOfRelayedTx( userTx *transaction.Transaction, ) (vmcommon.ReturnCode, error) { computedFees := txProc.computeRelayedTxFees(tx, userTx) - err := txProc.processTxAtRelayer(relayerAcnt, computedFees.totalFee, computedFees.relayerFee, tx) + txHash, err := txProc.processTxAtRelayer(relayerAcnt, computedFees.totalFee, computedFees.relayerFee, tx) if err != nil { return 0, err } @@ -635,27 +618,7 @@ func (txProc *txProcessor) finishExecutionOfRelayedTx( return 0, err } - originalTxHash, err := core.CalculateHash(txProc.marshalizer, txProc.hasher, tx) - if err != nil { - errRemove := txProc.removeValueAndConsumedFeeFromUser(userTx, tx.Value, originalTxHash, tx, err) - if errRemove != nil { - return vmcommon.UserError, errRemove - } - - return vmcommon.UserError, txProc.executeFailedRelayedUserTx( - userTx, - tx.SndAddr, - tx.Value, - tx.Nonce, - tx, - originalTxHash, - err.Error(), - nonRelayedV3UserTxIdx) - } - - defer txProc.saveFailedLogsIfNeeded(originalTxHash) - - return txProc.processUserTx(tx, userTx, tx.Value, tx.Nonce, originalTxHash, nonRelayedV3UserTxIdx) + return txProc.processUserTx(tx, userTx, tx.Value, tx.Nonce, txHash) } func (txProc *txProcessor) processTxAtRelayer( @@ -663,33 +626,33 @@ func (txProc *txProcessor) processTxAtRelayer( totalFee *big.Int, relayerFee *big.Int, tx *transaction.Transaction, -) error { +) ([]byte, error) { + txHash, err := core.CalculateHash(txProc.marshalizer, txProc.hasher, tx) + if err != nil { + return nil, err + } + if !check.IfNil(relayerAcnt) { - err := relayerAcnt.SubFromBalance(tx.GetValue()) + err = relayerAcnt.SubFromBalance(tx.GetValue()) if err != nil { - return err + return nil, err } err = relayerAcnt.SubFromBalance(totalFee) if err != nil { - return err + return nil, err } relayerAcnt.IncreaseNonce(1) err = txProc.accounts.SaveAccount(relayerAcnt) if err != nil { - return err - } - - txHash, err := core.CalculateHash(txProc.marshalizer, txProc.hasher, tx) - if err != nil { - return err + return nil, err } txProc.txFeeHandler.ProcessTransactionFee(relayerFee, big.NewInt(0), txHash) } - return nil + return txHash, nil } func (txProc *txProcessor) addFeeAndValueToDest(acntDst state.UserAccountHandler, txValue *big.Int, remainingFee *big.Int) error { @@ -706,132 +669,6 @@ func (txProc *txProcessor) addFeeAndValueToDest(acntDst state.UserAccountHandler return txProc.accounts.SaveAccount(acntDst) } -func (txProc *txProcessor) processRelayedTxV3( - tx *transaction.Transaction, - relayerAcnt state.UserAccountHandler, -) (vmcommon.ReturnCode, error) { - if !txProc.enableEpochsHandler.IsFlagEnabled(common.RelayedTransactionsV3Flag) { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrRelayedTxV3Disabled) - } - if check.IfNil(relayerAcnt) { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrNilRelayerAccount) - } - err := txProc.relayedTxV3Processor.CheckRelayedTx(tx) - if err != nil { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, err) - } - - snapshot := txProc.accounts.JournalLen() - - // process fees on both relayer and sender - relayerFee, totalFee, err := txProc.economicsFee.ComputeRelayedTxFees(tx) - if err != nil { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, err) - } - - err = txProc.processTxAtRelayer(relayerAcnt, totalFee, relayerFee, tx) - if err != nil { - return 0, err - } - - innerTxs := tx.GetInnerTransactions() - - originalTxHash, err := core.CalculateHash(txProc.marshalizer, txProc.hasher, tx) - if err != nil { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, err) - } - - var innerTxRetCode vmcommon.ReturnCode - var innerTxErr error - var innerTxFee *big.Int - innerTxsTotalFees := big.NewInt(0) - executedUserTxs := make([]*transaction.Transaction, 0) - for innerTxIdx, innerTx := range innerTxs { - innerTxFee, innerTxRetCode, innerTxErr = txProc.processInnerTx(tx, innerTx, originalTxHash, innerTxIdx) - innerTxsTotalFees.Add(innerTxsTotalFees, innerTxFee) - if innerTxErr != nil || innerTxRetCode != vmcommon.Ok { - continue - } - - executedUserTxs = append(executedUserTxs, innerTx) - } - - allUserTxsSucceeded := len(executedUserTxs) == len(innerTxs) && innerTxErr == nil && innerTxRetCode == vmcommon.Ok - if !allUserTxsSucceeded { - log.Trace("failed to execute all inner transactions", "total", len(innerTxs), "executed transactions", len(executedUserTxs)) - - txProc.saveFailedLogsIfNeeded(originalTxHash) - } - - expectedMaxInnerTxsTotalFees := big.NewInt(0).Sub(totalFee, relayerFee) - if innerTxsTotalFees.Cmp(expectedMaxInnerTxsTotalFees) > 0 { - log.Debug("reverting relayed transaction, total inner transactions fees mismatch", - "computed max fees at relayer", expectedMaxInnerTxsTotalFees.Uint64(), - "total inner fees consumed", innerTxsTotalFees.Uint64()) - - errRevert := txProc.accounts.RevertToSnapshot(snapshot) - if errRevert != nil { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, errRevert) - } - - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrConsumedFeesMismatch) - } - - return vmcommon.Ok, nil -} - -func (txProc *txProcessor) processInnerTx( - tx *transaction.Transaction, - innerTx *transaction.Transaction, - originalTxHash []byte, - innerTxIdx int, -) (*big.Int, vmcommon.ReturnCode, error) { - - txFee := txProc.computeInnerTxFee(innerTx) - - acntSnd, err := txProc.getAccountFromAddress(innerTx.SndAddr) - if err != nil { - return txFee, vmcommon.UserError, txProc.executeFailedRelayedUserTx( - innerTx, - innerTx.RelayerAddr, - big.NewInt(0), - tx.Nonce, - tx, - originalTxHash, - err.Error(), - innerTxIdx) - } - - if check.IfNil(acntSnd) { - return txFee, vmcommon.UserError, txProc.executeFailedRelayedUserTx( - innerTx, - innerTx.RelayerAddr, - big.NewInt(0), - tx.Nonce, - tx, - originalTxHash, - process.ErrRelayedTxV3SenderShardMismatch.Error(), - innerTxIdx) - } - - // TODO: remove adding and then removing the fee at the sender - err = txProc.addFeeAndValueToDest(acntSnd, big.NewInt(0), txFee) - if err != nil { - return txFee, vmcommon.UserError, txProc.executeFailedRelayedUserTx( - innerTx, - innerTx.RelayerAddr, - big.NewInt(0), - tx.Nonce, - tx, - originalTxHash, - err.Error(), - innerTxIdx) - } - - result, err := txProc.processUserTx(tx, innerTx, tx.Value, tx.Nonce, originalTxHash, innerTxIdx) - return txFee, result, err -} - func (txProc *txProcessor) processRelayedTxV2( tx *transaction.Transaction, relayerAcnt, acntDst state.UserAccountHandler, @@ -851,10 +688,6 @@ func (txProc *txProcessor) processRelayedTxV2( return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrInvalidArguments) } - if len(tx.InnerTransactions) > 0 { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrMultipleRelayedTxTypesIsNotAllowed) - } - userTx := makeUserTxFromRelayedTxV2Args(args) userTx.GasPrice = tx.GasPrice userTx.GasLimit = tx.GasLimit - txProc.economicsFee.ComputeGasLimit(tx) @@ -878,9 +711,6 @@ func (txProc *txProcessor) processRelayedTx( if !txProc.enableEpochsHandler.IsFlagEnabled(common.RelayedTransactionsFlag) { return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrRelayedTxDisabled) } - if len(tx.InnerTransactions) > 0 { - return vmcommon.UserError, txProc.executingFailedTransaction(tx, relayerAcnt, process.ErrMultipleRelayedTxTypesIsNotAllowed) - } userTx := &transaction.Transaction{} err = txProc.signMarshalizer.Unmarshal(userTx, args[0]) @@ -978,7 +808,7 @@ func (txProc *txProcessor) addNonExecutableLog(executionErr error, originalTxHas Address: originalTx.GetRcvAddr(), } - return txProc.failedTxLogsAccumulator.SaveLogs(originalTxHash, originalTx, []*vmcommon.LogEntry{logEntry}) + return txProc.txLogsProcessor.SaveLog(originalTxHash, originalTx, []*vmcommon.LogEntry{logEntry}) } @@ -1009,7 +839,6 @@ func (txProc *txProcessor) processUserTx( relayedTxValue *big.Int, relayedNonce uint64, originalTxHash []byte, - innerTxIdx int, ) (vmcommon.ReturnCode, error) { relayerAdr := originalTx.SndAddr @@ -1026,8 +855,7 @@ func (txProc *txProcessor) processUserTx( relayedNonce, originalTx, originalTxHash, - err.Error(), - innerTxIdx) + err.Error()) } txType, dstShardTxType := txProc.txTypeHandler.ComputeTransactionType(userTx) @@ -1044,8 +872,7 @@ func (txProc *txProcessor) processUserTx( relayedNonce, originalTx, originalTxHash, - err.Error(), - innerTxIdx) + err.Error()) } scrFromTx, err := txProc.makeSCRFromUserTx(userTx, relayerAdr, relayedTxValue, originalTxHash) @@ -1057,10 +884,6 @@ func (txProc *txProcessor) processUserTx( switch txType { case process.MoveBalance: err = txProc.processMoveBalance(userTx, acntSnd, acntDst, dstShardTxType, originalTxHash, true) - intraShard := txProc.shardCoordinator.SameShard(userTx.SndAddr, userTx.RcvAddr) - if err == nil && intraShard { - txProc.createCompleteEventLog(scrFromTx, originalTxHash) - } case process.SCDeployment: err = txProc.processMoveBalanceCostRelayedUserTx(userTx, scrFromTx, acntSnd, originalTxHash) if err != nil { @@ -1095,8 +918,7 @@ func (txProc *txProcessor) processUserTx( relayedNonce, originalTx, originalTxHash, - err.Error(), - innerTxIdx) + err.Error()) } if errors.Is(err, process.ErrInvalidMetaTransaction) || errors.Is(err, process.ErrAccountNotPayable) { @@ -1107,8 +929,7 @@ func (txProc *txProcessor) processUserTx( relayedNonce, originalTx, originalTxHash, - err.Error(), - innerTxIdx) + err.Error()) } if errors.Is(err, process.ErrFailedTransaction) { @@ -1186,14 +1007,8 @@ func (txProc *txProcessor) executeFailedRelayedUserTx( originalTx *transaction.Transaction, originalTxHash []byte, errorMsg string, - innerTxIdx int, ) error { - returnMessage := []byte(errorMsg) - isUserTxOfRelayedV3 := innerTxIdx != nonRelayedV3UserTxIdx - if isUserTxOfRelayedV3 { - returnMessage = []byte(fmt.Sprintf("%s while executing inner tx at index %d", errorMsg, innerTxIdx)) - } scrForRelayer := &smartContractResult.SmartContractResult{ Nonce: relayedNonce, Value: big.NewInt(0).Set(relayedTxValue), @@ -1201,7 +1016,7 @@ func (txProc *txProcessor) executeFailedRelayedUserTx( SndAddr: userTx.SndAddr, PrevTxHash: originalTxHash, OriginalTxHash: originalTxHash, - ReturnMessage: returnMessage, + ReturnMessage: []byte(errorMsg), } relayerAcnt, err := txProc.getAccountFromAddress(relayerAdr) @@ -1241,7 +1056,7 @@ func (txProc *txProcessor) executeFailedRelayedUserTx( return err } - if txProc.enableEpochsHandler.IsFlagEnabled(common.AddFailedRelayedTxToInvalidMBsFlag) && !isRelayedV3(originalTx.InnerTransactions) { + if txProc.enableEpochsHandler.IsFlagEnabled(common.AddFailedRelayedTxToInvalidMBsFlag) { err = txProc.badTxForwarder.AddIntermediateTransactions([]data.TransactionHandler{originalTx}, originalTxHash) if err != nil { return err @@ -1275,36 +1090,6 @@ func isNonExecutableError(executionErr error) bool { errors.Is(executionErr, process.ErrTransactionNotExecutable) } -func (txProc *txProcessor) createCompleteEventLog(scr data.TransactionHandler, originalTxHash []byte) { - scrHash, err := core.CalculateHash(txProc.marshalizer, txProc.hasher, scr) - if err != nil { - scrHash = originalTxHash - } - - completedTxLog := &vmcommon.LogEntry{ - Identifier: []byte(core.CompletedTxEventIdentifier), - Address: scr.GetRcvAddr(), - Topics: [][]byte{scrHash}, - } - - ignorableError := txProc.txLogsProcessor.SaveLog(scrHash, scr, []*vmcommon.LogEntry{completedTxLog}) - if ignorableError != nil { - log.Debug("txProcessor.createCompleteEventLog txLogsProcessor.SaveLog()", "error", ignorableError.Error()) - } -} - -func (txProc *txProcessor) saveFailedLogsIfNeeded(originalTxHash []byte) { - logsTx, logs, ok := txProc.failedTxLogsAccumulator.GetLogs(originalTxHash) - if ok { - ignorableErr := txProc.txLogsProcessor.SaveLog(originalTxHash, logsTx, logs) - if ignorableErr != nil { - log.Debug("txLogsProcessor.SaveLog failed", "error", ignorableErr.Error()) - } - } - - txProc.failedTxLogsAccumulator.Remove(originalTxHash) -} - // IsInterfaceNil returns true if there is no value under the interface func (txProc *txProcessor) IsInterfaceNil() bool { return txProc == nil diff --git a/process/transaction/shardProcess_test.go b/process/transaction/shardProcess_test.go index 4c325a8f78e..88797d31a0c 100644 --- a/process/transaction/shardProcess_test.go +++ b/process/transaction/shardProcess_test.go @@ -13,6 +13,7 @@ import ( "github.com/multiversx/mx-chain-core-go/data" "github.com/multiversx/mx-chain-core-go/data/smartContractResult" "github.com/multiversx/mx-chain-core-go/data/transaction" + "github.com/multiversx/mx-chain-core-go/marshal" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/multiversx/mx-chain-vm-common-go/builtInFunctions" "github.com/multiversx/mx-chain-vm-common-go/parsers" @@ -32,7 +33,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/guardianMocks" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" "github.com/multiversx/mx-chain-go/vm" ) @@ -79,27 +79,25 @@ func createAccountStub(sndAddr, rcvAddr []byte, func createArgsForTxProcessor() txproc.ArgsNewTxProcessor { args := txproc.ArgsNewTxProcessor{ - Accounts: &stateMock.AccountsStub{}, - Hasher: &hashingMocks.HasherMock{}, - PubkeyConv: createMockPubKeyConverter(), - Marshalizer: &mock.MarshalizerMock{}, - SignMarshalizer: &mock.MarshalizerMock{}, - ShardCoordinator: mock.NewOneShardCoordinatorMock(), - ScProcessor: &testscommon.SCProcessorMock{}, - TxFeeHandler: &mock.FeeAccumulatorStub{}, - TxTypeHandler: &testscommon.TxTypeHandlerMock{}, - EconomicsFee: feeHandlerMock(), - ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, - BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, - ArgsParser: &testscommon.ArgumentParserMock{}, - ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.PenalizedTooMuchGasFlag, common.FixRelayedBaseCostFlag), - GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, - TxVersionChecker: &testscommon.TxVersionCheckerStub{}, - TxLogsProcessor: &mock.TxLogsProcessorStub{}, - EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, - RelayedTxV3Processor: &processMocks.RelayedTxV3ProcessorMock{}, - FailedTxLogsAccumulator: &processMocks.FailedTxLogsAccumulatorMock{}, + Accounts: &stateMock.AccountsStub{}, + Hasher: &hashingMocks.HasherMock{}, + PubkeyConv: createMockPubKeyConverter(), + Marshalizer: &mock.MarshalizerMock{}, + SignMarshalizer: &mock.MarshalizerMock{}, + ShardCoordinator: mock.NewOneShardCoordinatorMock(), + ScProcessor: &testscommon.SCProcessorMock{}, + TxFeeHandler: &mock.FeeAccumulatorStub{}, + TxTypeHandler: &testscommon.TxTypeHandlerMock{}, + EconomicsFee: feeHandlerMock(), + ReceiptForwarder: &mock.IntermediateTransactionHandlerMock{}, + BadTxForwarder: &mock.IntermediateTransactionHandlerMock{}, + ArgsParser: &testscommon.ArgumentParserMock{}, + ScrForwarder: &mock.IntermediateTransactionHandlerMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.PenalizedTooMuchGasFlag, common.FixRelayedBaseCostFlag), + GuardianChecker: &guardianMocks.GuardedAccountHandlerStub{}, + TxVersionChecker: &testscommon.TxVersionCheckerStub{}, + TxLogsProcessor: &mock.TxLogsProcessorStub{}, + EnableRoundsHandler: &testscommon.EnableRoundsHandlerStub{}, } return args } @@ -331,28 +329,6 @@ func TestNewTxProcessor_NilGuardianCheckerShouldErr(t *testing.T) { assert.Nil(t, txProc) } -func TestNewTxProcessor_NilRelayedTxV3ProcessorShouldErr(t *testing.T) { - t.Parallel() - - args := createArgsForTxProcessor() - args.RelayedTxV3Processor = nil - txProc, err := txproc.NewTxProcessor(args) - - assert.Equal(t, process.ErrNilRelayedTxV3Processor, err) - assert.Nil(t, txProc) -} - -func TestNewTxProcessor_NilFailedTxLogsAccumulatorShouldErr(t *testing.T) { - t.Parallel() - - args := createArgsForTxProcessor() - args.FailedTxLogsAccumulator = nil - txProc, err := txproc.NewTxProcessor(args) - - assert.Equal(t, process.ErrNilFailedTxLogsAccumulator, err) - assert.Nil(t, txProc) -} - func TestNewTxProcessor_OkValsShouldWork(t *testing.T) { t.Parallel() @@ -2065,530 +2041,6 @@ func TestTxProcessor_ProcessRelayedTransactionV2(t *testing.T) { assert.Equal(t, vmcommon.Ok, returnCode) } -func TestTxProcessor_ProcessRelayedTransactionV3(t *testing.T) { - t.Parallel() - - marshaller := &mock.MarshalizerMock{} - - userAddr := []byte("user") - tx := &transaction.Transaction{} - tx.Nonce = 0 - tx.SndAddr = []byte("sSRC") - tx.RcvAddr = []byte("sSRC") - tx.Value = big.NewInt(0) - tx.GasPrice = 1 - tx.GasLimit = 8 - - userTx := &transaction.Transaction{} - userTx.Nonce = 0 - userTx.SndAddr = userAddr - userTx.RcvAddr = []byte("sDST") - userTx.Value = big.NewInt(0) - userTx.Data = []byte("execute@param1") - userTx.GasPrice = 1 - userTx.GasLimit = 4 - userTx.RelayerAddr = tx.SndAddr - - tx.InnerTransactions = []*transaction.Transaction{userTx} - - t.Run("flag not active should error", func(t *testing.T) { - t.Parallel() - - pubKeyConverter := testscommon.NewPubkeyConverterMock(4) - acntSrc := createUserAcc(tx.SndAddr) - _ = acntSrc.AddToBalance(big.NewInt(100)) - acntDst := createUserAcc(tx.RcvAddr) - _ = acntDst.AddToBalance(big.NewInt(10)) - - acntFinal := createUserAcc(userTx.RcvAddr) - _ = acntFinal.AddToBalance(big.NewInt(10)) - - adb := &stateMock.AccountsStub{} - adb.LoadAccountCalled = func(address []byte) (vmcommon.AccountHandler, error) { - if bytes.Equal(address, tx.SndAddr) { - return acntSrc, nil - } - if bytes.Equal(address, tx.RcvAddr) { - return acntDst, nil - } - if bytes.Equal(address, userTx.RcvAddr) { - return acntFinal, nil - } - - return nil, errors.New("failure") - } - - scProcessorMock := &testscommon.SCProcessorMock{} - shardC, _ := sharding.NewMultiShardCoordinator(1, 0) - esdtTransferParser, _ := parsers.NewESDTTransferParser(marshaller) - argTxTypeHandler := coordinator.ArgNewTxTypeHandler{ - PubkeyConverter: pubKeyConverter, - ShardCoordinator: shardC, - BuiltInFunctions: builtInFunctions.NewBuiltInFunctionContainer(), - ArgumentParser: parsers.NewCallArgsParser(), - ESDTTransferParser: esdtTransferParser, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.ESDTMetadataContinuousCleanupFlag), - } - txTypeHandler, _ := coordinator.NewTxTypeHandler(argTxTypeHandler) - - args := createArgsForTxProcessor() - args.Accounts = adb - args.ScProcessor = scProcessorMock - args.ShardCoordinator = shardC - args.TxTypeHandler = txTypeHandler - args.PubkeyConv = pubKeyConverter - args.ArgsParser = smartContract.NewArgumentParser() - args.EnableEpochsHandler = &enableEpochsHandlerMock.EnableEpochsHandlerStub{} - execTx, _ := txproc.NewTxProcessor(args) - - returnCode, err := execTx.ProcessTransaction(tx) - assert.Equal(t, process.ErrFailedTransaction, err) - assert.Equal(t, vmcommon.UserError, returnCode) - }) - t.Run("value on parent tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - txCopy.Value = big.NewInt(1) - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("different receiver on tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - txCopy.RcvAddr = userTx.SndAddr - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("empty relayer on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - userTxCopy := *userTx - userTxCopy.RelayerAddr = nil - txCopy.InnerTransactions = []*transaction.Transaction{&userTxCopy} - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("different relayer on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - userTxCopy := *userTx - userTxCopy.RelayerAddr = []byte("other") - txCopy.InnerTransactions = []*transaction.Transaction{&userTxCopy} - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("different gas price on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - txCopy.GasPrice = userTx.GasPrice + 1 - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("higher gas limit on inner tx should error", func(t *testing.T) { - t.Parallel() - - txCopy := *tx - txCopy.GasLimit = userTx.GasLimit - 1 - testProcessRelayedTransactionV3(t, &txCopy, userTx.SndAddr, userTx.RcvAddr, process.ErrFailedTransaction, vmcommon.UserError) - }) - t.Run("failure to add fees on destination should skip transaction and continue", func(t *testing.T) { - t.Parallel() - - providedAddrFail := []byte("fail addr") - providedInitialBalance := big.NewInt(100) - pubKeyConverter := testscommon.NewPubkeyConverterMock(4) - - accounts := map[string]state.UserAccountHandler{} - adb := &stateMock.AccountsStub{} - adb.LoadAccountCalled = func(address []byte) (vmcommon.AccountHandler, error) { - if bytes.Equal(address, providedAddrFail) { - return &stateMock.UserAccountStub{ - AddToBalanceCalled: func(value *big.Int) error { - return errors.New("won't add to balance") - }, - }, nil - } - - acnt, exists := accounts[string(address)] - if !exists { - acnt = createUserAcc(address) - accounts[string(address)] = acnt - _ = acnt.AddToBalance(providedInitialBalance) - } - - return acnt, nil - } - - scProcessorMock := &testscommon.SCProcessorMock{} - shardC, _ := sharding.NewMultiShardCoordinator(1, 0) - esdtTransferParser, _ := parsers.NewESDTTransferParser(marshaller) - argTxTypeHandler := coordinator.ArgNewTxTypeHandler{ - PubkeyConverter: pubKeyConverter, - ShardCoordinator: shardC, - BuiltInFunctions: builtInFunctions.NewBuiltInFunctionContainer(), - ArgumentParser: parsers.NewCallArgsParser(), - ESDTTransferParser: esdtTransferParser, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.ESDTMetadataContinuousCleanupFlag), - } - txTypeHandler, _ := coordinator.NewTxTypeHandler(argTxTypeHandler) - - args := createArgsForTxProcessor() - args.Accounts = adb - args.ScProcessor = scProcessorMock - args.ShardCoordinator = shardC - args.TxTypeHandler = txTypeHandler - args.PubkeyConv = pubKeyConverter - args.ArgsParser = smartContract.NewArgumentParser() - args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag) - args.EconomicsFee = &economicsmocks.EconomicsHandlerStub{ - ComputeMoveBalanceFeeCalled: func(tx data.TransactionWithFeeHandler) *big.Int { - return big.NewInt(1) - }, - ComputeRelayedTxFeesCalled: func(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - relayerFee := big.NewInt(0).SetInt64(int64(len(tx.GetUserTransactions()))) // gasPrice = 1 - totalFee := *relayerFee - for _, innerTx := range tx.GetUserTransactions() { - totalFee.Add(&totalFee, big.NewInt(0).SetUint64(innerTx.GetGasLimit())) - } - - return relayerFee, &totalFee, nil - }, - } - args.RelayedTxV3Processor, _ = txproc.NewRelayedTxV3Processor(txproc.ArgRelayedTxV3Processor{ - EconomicsFee: args.EconomicsFee, - ShardCoordinator: args.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - logs := make([]*vmcommon.LogEntry, 0) - args.TxLogsProcessor = &mock.TxLogsProcessorStub{ - SaveLogCalled: func(txHash []byte, tx data.TransactionHandler, vmLogs []*vmcommon.LogEntry) error { - logs = append(logs, vmLogs...) - return nil - }, - } - execTx, _ := txproc.NewTxProcessor(args) - - txCopy := *tx - innerTx1 := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(10), - RcvAddr: []byte("sDST"), - SndAddr: []byte("sender inner tx 1"), - GasPrice: 1, - GasLimit: 1, - RelayerAddr: txCopy.SndAddr, - } - innerTx2 := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(10), - RcvAddr: []byte("sDST"), - SndAddr: []byte("sender inner tx 2"), - GasPrice: 1, - GasLimit: 1, - RelayerAddr: txCopy.SndAddr, - } - innerTx3 := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(10), - RcvAddr: []byte("sDST"), - SndAddr: providedAddrFail, - GasPrice: 1, - GasLimit: 1, - RelayerAddr: txCopy.SndAddr, - } - - txCopy.InnerTransactions = []*transaction.Transaction{innerTx1, innerTx2, innerTx3} - returnCode, err := execTx.ProcessTransaction(&txCopy) - assert.NoError(t, err) - assert.Equal(t, vmcommon.Ok, returnCode) - - expectedBalance := providedInitialBalance - for _, acnt := range accounts { - switch string(acnt.AddressBytes()) { - case "sSRC": - continue // relayer - case "sDST": - expectedBalance = big.NewInt(120) // 2 successful txs received - case "sender inner tx 1", "sender inner tx 2": - expectedBalance = big.NewInt(90) // one successful tx sent from each - default: - assert.Fail(t, "should not be other participants") - } - - assert.Equal(t, expectedBalance, acnt.GetBalance(), fmt.Sprintf("checks failed for address: %s", string(acnt.AddressBytes()))) - } - - require.Equal(t, 2, len(logs)) - for _, log := range logs { - require.Equal(t, core.CompletedTxEventIdentifier, string(log.Identifier)) - } - }) - t.Run("one inner fails should return success on relayed", func(t *testing.T) { - t.Parallel() - - providedInitialBalance := big.NewInt(100) - pubKeyConverter := testscommon.NewPubkeyConverterMock(4) - - accounts := map[string]state.UserAccountHandler{} - adb := &stateMock.AccountsStub{} - adb.LoadAccountCalled = func(address []byte) (vmcommon.AccountHandler, error) { - acnt, exists := accounts[string(address)] - if !exists { - acnt = createUserAcc(address) - accounts[string(address)] = acnt - _ = acnt.AddToBalance(providedInitialBalance) - } - - return acnt, nil - } - - scProcessorMock := &testscommon.SCProcessorMock{} - shardC, _ := sharding.NewMultiShardCoordinator(1, 0) - esdtTransferParser, _ := parsers.NewESDTTransferParser(marshaller) - argTxTypeHandler := coordinator.ArgNewTxTypeHandler{ - PubkeyConverter: pubKeyConverter, - ShardCoordinator: shardC, - BuiltInFunctions: builtInFunctions.NewBuiltInFunctionContainer(), - ArgumentParser: parsers.NewCallArgsParser(), - ESDTTransferParser: esdtTransferParser, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.ESDTMetadataContinuousCleanupFlag), - } - txTypeHandler, _ := coordinator.NewTxTypeHandler(argTxTypeHandler) - - args := createArgsForTxProcessor() - args.Accounts = adb - args.ScProcessor = scProcessorMock - args.ShardCoordinator = shardC - args.TxTypeHandler = txTypeHandler - args.PubkeyConv = pubKeyConverter - args.ArgsParser = smartContract.NewArgumentParser() - args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag) - args.EconomicsFee = &economicsmocks.EconomicsHandlerStub{ - ComputeMoveBalanceFeeCalled: func(tx data.TransactionWithFeeHandler) *big.Int { - return big.NewInt(int64(tx.GetGasPrice() * tx.GetGasLimit())) - }, - ComputeRelayedTxFeesCalled: func(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - relayerFee := big.NewInt(0).SetInt64(int64(len(tx.GetUserTransactions()))) // gasPrice = 1 - totalFee := *relayerFee - for _, innerTx := range tx.GetUserTransactions() { - totalFee.Add(&totalFee, big.NewInt(0).SetUint64(innerTx.GetGasLimit())) - } - - return relayerFee, &totalFee, nil - }, - } - args.RelayedTxV3Processor, _ = txproc.NewRelayedTxV3Processor(txproc.ArgRelayedTxV3Processor{ - EconomicsFee: args.EconomicsFee, - ShardCoordinator: args.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - wasGetLogsCalled := false - wasRemoveCalled := false - args.FailedTxLogsAccumulator = &processMocks.FailedTxLogsAccumulatorMock{ - GetLogsCalled: func(txHash []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) { - wasGetLogsCalled = true - - return &smartContractResult.SmartContractResult{}, []*vmcommon.LogEntry{}, true - }, - RemoveCalled: func(txHash []byte) { - wasRemoveCalled = true - }, - } - execTx, _ := txproc.NewTxProcessor(args) - - txCopy := *tx - usertTxCopy := *userTx // same inner tx twice should fail second time - txCopy.InnerTransactions = append(txCopy.InnerTransactions, &usertTxCopy) - returnCode, err := execTx.ProcessTransaction(&txCopy) - assert.NoError(t, err) - assert.Equal(t, vmcommon.Ok, returnCode) - assert.True(t, wasGetLogsCalled) - assert.True(t, wasRemoveCalled) - }) - t.Run("fees consumed mismatch should error", func(t *testing.T) { - t.Parallel() - - providedInitialBalance := big.NewInt(100) - pubKeyConverter := testscommon.NewPubkeyConverterMock(4) - - accounts := map[string]state.UserAccountHandler{} - adb := &stateMock.AccountsStub{} - adb.LoadAccountCalled = func(address []byte) (vmcommon.AccountHandler, error) { - acnt, exists := accounts[string(address)] - if !exists { - acnt = createUserAcc(address) - accounts[string(address)] = acnt - _ = acnt.AddToBalance(providedInitialBalance) - } - - return acnt, nil - } - wasRevertToSnapshotCalled := false - adb.RevertToSnapshotCalled = func(snapshot int) error { - wasRevertToSnapshotCalled = true - return nil - } - - scProcessorMock := &testscommon.SCProcessorMock{} - shardC, _ := sharding.NewMultiShardCoordinator(1, 0) - esdtTransferParser, _ := parsers.NewESDTTransferParser(marshaller) - argTxTypeHandler := coordinator.ArgNewTxTypeHandler{ - PubkeyConverter: pubKeyConverter, - ShardCoordinator: shardC, - BuiltInFunctions: builtInFunctions.NewBuiltInFunctionContainer(), - ArgumentParser: parsers.NewCallArgsParser(), - ESDTTransferParser: esdtTransferParser, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.ESDTMetadataContinuousCleanupFlag), - } - txTypeHandler, _ := coordinator.NewTxTypeHandler(argTxTypeHandler) - - args := createArgsForTxProcessor() - args.Accounts = adb - args.ScProcessor = scProcessorMock - args.ShardCoordinator = shardC - args.TxTypeHandler = txTypeHandler - args.PubkeyConv = pubKeyConverter - args.ArgsParser = smartContract.NewArgumentParser() - args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag) - increasingFee := big.NewInt(0) - args.EconomicsFee = &economicsmocks.EconomicsHandlerStub{ - ComputeMoveBalanceFeeCalled: func(tx data.TransactionWithFeeHandler) *big.Int { - increasingFee.Add(increasingFee, big.NewInt(1)) - return increasingFee - }, - } - args.RelayedTxV3Processor, _ = txproc.NewRelayedTxV3Processor(txproc.ArgRelayedTxV3Processor{ - EconomicsFee: args.EconomicsFee, - ShardCoordinator: args.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - execTx, _ := txproc.NewTxProcessor(args) - - txCopy := *tx - innerTx1 := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(10), - RcvAddr: []byte("sDST"), - SndAddr: []byte("sender inner tx 1"), - GasPrice: 1, - GasLimit: 1, - RelayerAddr: txCopy.SndAddr, - } - innerTx2 := &transaction.Transaction{ - Nonce: 0, - Value: big.NewInt(10), - RcvAddr: []byte("sDST"), - SndAddr: []byte("sender inner tx 2"), - GasPrice: 1, - GasLimit: 1, - RelayerAddr: txCopy.SndAddr, - } - - txCopy.InnerTransactions = []*transaction.Transaction{innerTx1, innerTx2} - returnCode, err := execTx.ProcessTransaction(&txCopy) - assert.Error(t, err) - assert.Equal(t, vmcommon.UserError, returnCode) - assert.True(t, wasRevertToSnapshotCalled) - }) - t.Run("should work", func(t *testing.T) { - t.Parallel() - testProcessRelayedTransactionV3(t, tx, userTx.SndAddr, userTx.RcvAddr, nil, vmcommon.Ok) - }) -} - -func testProcessRelayedTransactionV3( - t *testing.T, - tx *transaction.Transaction, - innerSender []byte, - finalRcvr []byte, - expectedErr error, - expectedCode vmcommon.ReturnCode, -) { - pubKeyConverter := testscommon.NewPubkeyConverterMock(4) - marshaller := &mock.MarshalizerMock{} - - acntSrc := createUserAcc(tx.SndAddr) - _ = acntSrc.AddToBalance(big.NewInt(100)) - acntDst := createUserAcc(tx.RcvAddr) - _ = acntDst.AddToBalance(big.NewInt(10)) - - acntFinal := createUserAcc(finalRcvr) - _ = acntFinal.AddToBalance(big.NewInt(10)) - acntInnerSender := createUserAcc(innerSender) - _ = acntInnerSender.AddToBalance(big.NewInt(10)) - - adb := &stateMock.AccountsStub{} - adb.LoadAccountCalled = func(address []byte) (vmcommon.AccountHandler, error) { - if bytes.Equal(address, tx.SndAddr) { - return acntSrc, nil - } - if bytes.Equal(address, tx.RcvAddr) { - return acntDst, nil - } - if bytes.Equal(address, finalRcvr) { - return acntFinal, nil - } - if bytes.Equal(address, innerSender) { - return acntInnerSender, nil - } - - return nil, errors.New("failure") - } - - scProcessorMock := &testscommon.SCProcessorMock{} - shardC, _ := sharding.NewMultiShardCoordinator(1, 0) - esdtTransferParser, _ := parsers.NewESDTTransferParser(marshaller) - argTxTypeHandler := coordinator.ArgNewTxTypeHandler{ - PubkeyConverter: pubKeyConverter, - ShardCoordinator: shardC, - BuiltInFunctions: builtInFunctions.NewBuiltInFunctionContainer(), - ArgumentParser: parsers.NewCallArgsParser(), - ESDTTransferParser: esdtTransferParser, - EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.ESDTMetadataContinuousCleanupFlag), - } - txTypeHandler, _ := coordinator.NewTxTypeHandler(argTxTypeHandler) - - args := createArgsForTxProcessor() - args.Accounts = adb - args.ScProcessor = scProcessorMock - args.ShardCoordinator = shardC - args.TxTypeHandler = txTypeHandler - args.PubkeyConv = pubKeyConverter - args.ArgsParser = smartContract.NewArgumentParser() - args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub(common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag) - args.EconomicsFee = &economicsmocks.EconomicsHandlerMock{ - ComputeTxFeeCalled: func(tx data.TransactionWithFeeHandler) *big.Int { - return big.NewInt(4) - }, - ComputeMoveBalanceFeeCalled: func(tx data.TransactionWithFeeHandler) *big.Int { - return big.NewInt(4) - }, - ComputeGasLimitCalled: func(tx data.TransactionWithFeeHandler) uint64 { - return 4 - }, - ComputeRelayedTxFeesCalled: func(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - relayerFee := big.NewInt(0).SetInt64(int64(len(tx.GetUserTransactions()))) // gasPrice = 1 - totalFee := *relayerFee - for _, innerTx := range tx.GetUserTransactions() { - totalFee.Add(&totalFee, big.NewInt(0).SetUint64(innerTx.GetGasLimit())) - } - - return relayerFee, &totalFee, nil - }, - } - args.RelayedTxV3Processor, _ = txproc.NewRelayedTxV3Processor(txproc.ArgRelayedTxV3Processor{ - EconomicsFee: args.EconomicsFee, - ShardCoordinator: args.ShardCoordinator, - MaxTransactionsAllowed: 10, - }) - - execTx, _ := txproc.NewTxProcessor(args) - - returnCode, err := execTx.ProcessTransaction(tx) - assert.Equal(t, expectedErr, err) - assert.Equal(t, expectedCode, returnCode) -} - func TestTxProcessor_ProcessRelayedTransaction(t *testing.T) { t.Parallel() @@ -3846,12 +3298,12 @@ func TestTxProcessor_AddNonExecutableLog(t *testing.T) { originalTxHash, err := core.CalculateHash(args.Marshalizer, args.Hasher, originalTx) assert.Nil(t, err) numLogsSaved := 0 - args.FailedTxLogsAccumulator = &processMocks.FailedTxLogsAccumulatorMock{ - SaveLogsCalled: func(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error { + args.TxLogsProcessor = &mock.TxLogsProcessorStub{ + SaveLogCalled: func(txHash []byte, tx data.TransactionHandler, vmLogs []*vmcommon.LogEntry) error { assert.Equal(t, originalTxHash, txHash) assert.Equal(t, originalTx, tx) - assert.Equal(t, 1, len(logs)) - firstLog := logs[0] + assert.Equal(t, 1, len(vmLogs)) + firstLog := vmLogs[0] assert.Equal(t, core.SignalErrorOperation, string(firstLog.Identifier)) assert.Equal(t, sender, firstLog.Address) assert.Empty(t, firstLog.Data) @@ -3880,20 +3332,21 @@ func TestTxProcessor_ProcessMoveBalanceToNonPayableContract(t *testing.T) { t.Parallel() shardCoordinator := mock.NewOneShardCoordinatorMock() + marshaller := marshal.JsonMarshalizer{} innerTx := transaction.Transaction{} innerTx.Nonce = 1 innerTx.SndAddr = []byte("SRC") innerTx.RcvAddr = make([]byte, 32) innerTx.Value = big.NewInt(100) - innerTx.RelayerAddr = []byte("SRC") tx := transaction.Transaction{} tx.Nonce = 0 tx.SndAddr = []byte("SRC") tx.RcvAddr = []byte("SRC") tx.Value = big.NewInt(0) - tx.InnerTransactions = []*transaction.Transaction{&innerTx} + marshalledData, _ := marshaller.Marshal(&innerTx) + tx.Data = []byte("relayedTx@" + hex.EncodeToString(marshalledData)) shardCoordinator.ComputeIdCalled = func(address []byte) uint32 { return 0 @@ -3909,19 +3362,20 @@ func TestTxProcessor_ProcessMoveBalanceToNonPayableContract(t *testing.T) { args := createArgsForTxProcessor() args.Accounts = adb args.ShardCoordinator = shardCoordinator + args.SignMarshalizer = &marshaller cnt := 0 args.TxTypeHandler = &testscommon.TxTypeHandlerMock{ ComputeTransactionTypeCalled: func(tx data.TransactionHandler) (process.TransactionType, process.TransactionType) { cnt++ if cnt == 1 { - return process.RelayedTxV3, process.RelayedTxV3 + return process.RelayedTx, process.RelayedTx } return process.MoveBalance, process.MoveBalance }, } args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub( - common.RelayedTransactionsV3Flag, + common.RelayedTransactionsFlag, common.FixRelayedBaseCostFlag, common.FixRelayedMoveBalanceToNonPayableSCFlag, ) @@ -3930,6 +3384,11 @@ func TestTxProcessor_ProcessMoveBalanceToNonPayableContract(t *testing.T) { return false, nil }, } + args.ArgsParser = &testscommon.ArgumentParserMock{ + ParseCallDataCalled: func(data string) (string, [][]byte, error) { + return core.RelayedTransaction, [][]byte{marshalledData}, nil + }, + } execTx, _ := txproc.NewTxProcessor(args) _, err := execTx.ProcessTransaction(&tx) @@ -3943,7 +3402,7 @@ func TestTxProcessor_IsInterfaceNil(t *testing.T) { t.Parallel() args := createArgsForTxProcessor() - args.RelayedTxV3Processor = nil + args.Hasher = nil proc, _ := txproc.NewTxProcessor(args) require.True(t, proc.IsInterfaceNil()) diff --git a/process/transactionEvaluator/transactionEvaluator.go b/process/transactionEvaluator/transactionEvaluator.go index 032aeefdc80..9e61d138419 100644 --- a/process/transactionEvaluator/transactionEvaluator.go +++ b/process/transactionEvaluator/transactionEvaluator.go @@ -119,7 +119,7 @@ func (ate *apiTransactionEvaluator) ComputeTransactionGasLimit(tx *transaction.T switch txTypeOnSender { case process.SCDeployment, process.SCInvoking, process.BuiltInFunctionCall, process.MoveBalance: return ate.simulateTransactionCost(tx, txTypeOnSender) - case process.RelayedTx, process.RelayedTxV2, process.RelayedTxV3: + case process.RelayedTx, process.RelayedTxV2: // TODO implement in the next PR return &transaction.CostResponse{ GasUnits: 0, diff --git a/process/transactionLog/failedTxLogsAccumulator.go b/process/transactionLog/failedTxLogsAccumulator.go deleted file mode 100644 index a0d973541bc..00000000000 --- a/process/transactionLog/failedTxLogsAccumulator.go +++ /dev/null @@ -1,109 +0,0 @@ -package transactionLog - -import ( - "sync" - - "github.com/multiversx/mx-chain-core-go/core/check" - "github.com/multiversx/mx-chain-core-go/data" - "github.com/multiversx/mx-chain-go/process" - vmcommon "github.com/multiversx/mx-chain-vm-common-go" -) - -type logData struct { - tx data.TransactionHandler - logs []*vmcommon.LogEntry -} - -type failedTxLogsAccumulator struct { - mut sync.RWMutex - logsMap map[string]*logData -} - -// NewFailedTxLogsAccumulator returns a new instance of failedTxLogsAccumulator -func NewFailedTxLogsAccumulator() *failedTxLogsAccumulator { - return &failedTxLogsAccumulator{ - logsMap: make(map[string]*logData), - } -} - -// GetLogs returns the accumulated logs for the provided txHash -func (accumulator *failedTxLogsAccumulator) GetLogs(txHash []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) { - if len(txHash) == 0 { - return nil, nil, false - } - - logsData, found := accumulator.getLogDataCopy(txHash) - - if !found { - return nil, nil, found - } - - return logsData.tx, logsData.logs, found -} - -func (accumulator *failedTxLogsAccumulator) getLogDataCopy(txHash []byte) (logData, bool) { - accumulator.mut.RLock() - defer accumulator.mut.RUnlock() - - logsData, found := accumulator.logsMap[string(txHash)] - if !found { - return logData{}, found - } - - logsDataCopy := logData{ - tx: logsData.tx, - } - - logsDataCopy.logs = append(logsDataCopy.logs, logsData.logs...) - - return logsDataCopy, found -} - -// SaveLogs saves the logs into the internal map -func (accumulator *failedTxLogsAccumulator) SaveLogs(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error { - if len(txHash) == 0 { - return process.ErrNilTxHash - } - - if check.IfNil(tx) { - return process.ErrNilTransaction - } - - if len(logs) == 0 { - return nil - } - - accumulator.mut.Lock() - defer accumulator.mut.Unlock() - - _, found := accumulator.logsMap[string(txHash)] - if !found { - accumulator.logsMap[string(txHash)] = &logData{ - tx: tx, - logs: logs, - } - - return nil - } - - accumulator.logsMap[string(txHash)].logs = append(accumulator.logsMap[string(txHash)].logs, logs...) - - return nil -} - -// Remove removes the accumulated logs for the provided txHash -func (accumulator *failedTxLogsAccumulator) Remove(txHash []byte) { - if len(txHash) == 0 { - return - } - - accumulator.mut.Lock() - defer accumulator.mut.Unlock() - - delete(accumulator.logsMap, string(txHash)) -} - -// IsInterfaceNil returns true if there is no value under the interface -func (accumulator *failedTxLogsAccumulator) IsInterfaceNil() bool { - return accumulator == nil -} diff --git a/process/transactionLog/failedTxLogsAccumulator_test.go b/process/transactionLog/failedTxLogsAccumulator_test.go deleted file mode 100644 index 691f4b41ffa..00000000000 --- a/process/transactionLog/failedTxLogsAccumulator_test.go +++ /dev/null @@ -1,168 +0,0 @@ -package transactionLog - -import ( - "fmt" - "sync" - "testing" - - "github.com/multiversx/mx-chain-core-go/data/transaction" - "github.com/multiversx/mx-chain-go/process" - vmcommon "github.com/multiversx/mx-chain-vm-common-go" - "github.com/stretchr/testify/require" -) - -var ( - providedHash = []byte("hash") - providedTx = &transaction.Transaction{Nonce: 123} - providedLogs = []*vmcommon.LogEntry{ - { - Identifier: []byte("identifier"), - Address: []byte("addr"), - Topics: [][]byte{[]byte("topic")}, - Data: [][]byte{[]byte("data")}, - }, - } -) - -func TestNewFailedTxLogsAccumulator(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - require.NotNil(t, accumulator) -} - -func TestFailedTxLogsAccumulator_IsInterfaceNil(t *testing.T) { - t.Parallel() - - var accumulator *failedTxLogsAccumulator - require.True(t, accumulator.IsInterfaceNil()) - - accumulator = NewFailedTxLogsAccumulator() - require.False(t, accumulator.IsInterfaceNil()) -} - -func TestFailedTxLogsAccumulator_GetLogs(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - tx, logs, ok := accumulator.GetLogs([]byte("")) - require.False(t, ok) - require.Nil(t, tx) - require.Nil(t, logs) - - err := accumulator.SaveLogs(providedHash, providedTx, providedLogs) - require.NoError(t, err) - - tx, logs, ok = accumulator.GetLogs([]byte("missing hash")) - require.False(t, ok) - require.Nil(t, tx) - require.Nil(t, logs) - - tx, logs, ok = accumulator.GetLogs(providedHash) - require.True(t, ok) - require.Equal(t, providedTx, tx) - require.Equal(t, providedLogs, logs) -} - -func TestFailedTxLogsAccumulator_SaveLogs(t *testing.T) { - t.Parallel() - - t.Run("empty hash should error", func(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - err := accumulator.SaveLogs([]byte(""), nil, nil) - require.Equal(t, process.ErrNilTxHash, err) - }) - t.Run("nil tx should error", func(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - err := accumulator.SaveLogs(providedHash, nil, nil) - require.Equal(t, process.ErrNilTransaction, err) - }) - t.Run("empty logs should return nil", func(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - err := accumulator.SaveLogs(providedHash, providedTx, nil) - require.NoError(t, err) - }) - t.Run("should work and append logs", func(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - err := accumulator.SaveLogs(providedHash, providedTx, providedLogs) - require.NoError(t, err) - - providedNewLogs := []*vmcommon.LogEntry{ - { - Identifier: []byte("identifier 2"), - Address: []byte("addr"), - Topics: [][]byte{[]byte("topic 2")}, - Data: [][]byte{[]byte("data 2")}, - }, - } - err = accumulator.SaveLogs(providedHash, providedTx, providedNewLogs) - require.NoError(t, err) - - expectedLogs := append(providedLogs, providedNewLogs...) - receivedTx, receivedLogs, ok := accumulator.GetLogs(providedHash) - require.True(t, ok) - require.Equal(t, providedTx, receivedTx) - require.Equal(t, expectedLogs, receivedLogs) - }) -} - -func TestFailedTxLogsAccumulator_Remove(t *testing.T) { - t.Parallel() - - accumulator := NewFailedTxLogsAccumulator() - err := accumulator.SaveLogs(providedHash, providedTx, providedLogs) - require.NoError(t, err) - _, _, ok := accumulator.GetLogs(providedHash) - require.True(t, ok) - - accumulator.Remove([]byte("")) // coverage only - - accumulator.Remove(providedHash) - _, _, ok = accumulator.GetLogs(providedHash) - require.False(t, ok) -} - -func TestTxLogProcessor_ConcurrentOperations(t *testing.T) { - t.Parallel() - - require.NotPanics(t, func() { - accumulator := NewFailedTxLogsAccumulator() - - numCalls := 1000 - wg := sync.WaitGroup{} - wg.Add(numCalls) - - for i := 0; i < numCalls; i++ { - go func(idx int) { - switch idx % 3 { - case 0: - err := accumulator.SaveLogs(providedHash, providedTx, []*vmcommon.LogEntry{ - { - Identifier: []byte(fmt.Sprintf("identifier %d", idx)), - Address: []byte("addr"), - Topics: [][]byte{[]byte(fmt.Sprintf("topic %d", idx))}, - Data: [][]byte{[]byte(fmt.Sprintf("data %d", idx))}, - }, - }) - require.NoError(t, err) - case 1: - _, _, _ = accumulator.GetLogs(providedHash) - case 2: - accumulator.Remove(providedHash) - } - - wg.Done() - }(i) - } - - wg.Wait() - }) -} diff --git a/sharding/mock/enableEpochsHandlerMock.go b/sharding/mock/enableEpochsHandlerMock.go index 9a842f9adae..48dfcedfa52 100644 --- a/sharding/mock/enableEpochsHandlerMock.go +++ b/sharding/mock/enableEpochsHandlerMock.go @@ -43,21 +43,6 @@ func (mock *EnableEpochsHandlerMock) GetCurrentEpoch() uint32 { return mock.CurrentEpoch } -// FixGasRemainingForSaveKeyValueBuiltinFunctionEnabled - -func (mock *EnableEpochsHandlerMock) FixGasRemainingForSaveKeyValueBuiltinFunctionEnabled() bool { - return false -} - -// IsRelayedTransactionsV3FlagEnabled - -func (mock *EnableEpochsHandlerMock) IsRelayedTransactionsV3FlagEnabled() bool { - return false -} - -// IsFixRelayedBaseCostFlagEnabled - -func (mock *EnableEpochsHandlerMock) IsFixRelayedBaseCostFlagEnabled() bool { - return false -} - // IsInterfaceNil returns true if there is no value under the interface func (mock *EnableEpochsHandlerMock) IsInterfaceNil() bool { return mock == nil diff --git a/testscommon/components/default.go b/testscommon/components/default.go index 8e1942037dd..514b8355407 100644 --- a/testscommon/components/default.go +++ b/testscommon/components/default.go @@ -20,7 +20,6 @@ import ( "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" "github.com/multiversx/mx-chain-go/testscommon/nodeTypeProviderMock" "github.com/multiversx/mx-chain-go/testscommon/p2pmocks" - "github.com/multiversx/mx-chain-go/testscommon/processMocks" "github.com/multiversx/mx-chain-go/testscommon/shardingMocks" "github.com/multiversx/mx-chain-go/testscommon/stakingcommon" stateMock "github.com/multiversx/mx-chain-go/testscommon/state" @@ -157,7 +156,6 @@ func GetDefaultProcessComponents(shardCoordinator sharding.Coordinator) *mock.Pr return &mock.PrivateKeyStub{} }, }, - HardforkTriggerField: &testscommon.HardforkTriggerStub{}, - RelayedTxV3ProcessorField: &processMocks.RelayedTxV3ProcessorMock{}, + HardforkTriggerField: &testscommon.HardforkTriggerStub{}, } } diff --git a/testscommon/economicsmocks/economicsDataHandlerStub.go b/testscommon/economicsmocks/economicsDataHandlerStub.go index c76ce6c59a2..4ef784c596f 100644 --- a/testscommon/economicsmocks/economicsDataHandlerStub.go +++ b/testscommon/economicsmocks/economicsDataHandlerStub.go @@ -5,7 +5,6 @@ import ( "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/data" - "github.com/multiversx/mx-chain-go/process" ) // EconomicsHandlerStub - @@ -47,8 +46,6 @@ type EconomicsHandlerStub struct { ComputeGasLimitInEpochCalled func(tx data.TransactionWithFeeHandler, epoch uint32) uint64 ComputeGasUsedAndFeeBasedOnRefundValueInEpochCalled func(tx data.TransactionWithFeeHandler, refundValue *big.Int, epoch uint32) (uint64, *big.Int) ComputeTxFeeBasedOnGasUsedInEpochCalled func(tx data.TransactionWithFeeHandler, gasUsed uint64, epoch uint32) *big.Int - ComputeRelayedTxFeesCalled func(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) - SetTxTypeHandlerCalled func(txTypeHandler process.TxTypeHandler) error ComputeMoveBalanceFeeInEpochCalled func(tx data.TransactionWithFeeHandler, epoch uint32) *big.Int } @@ -368,22 +365,6 @@ func (e *EconomicsHandlerStub) ComputeTxFeeBasedOnGasUsedInEpoch(tx data.Transac return nil } -// ComputeRelayedTxFees - -func (e *EconomicsHandlerStub) ComputeRelayedTxFees(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - if e.ComputeRelayedTxFeesCalled != nil { - return e.ComputeRelayedTxFeesCalled(tx) - } - return big.NewInt(0), big.NewInt(0), nil -} - -// SetTxTypeHandler - -func (e *EconomicsHandlerStub) SetTxTypeHandler(txTypeHandler process.TxTypeHandler) error { - if e.SetTxTypeHandlerCalled != nil { - return e.SetTxTypeHandlerCalled(txTypeHandler) - } - return nil -} - // IsInterfaceNil returns true if there is no value under the interface func (e *EconomicsHandlerStub) IsInterfaceNil() bool { return e == nil diff --git a/testscommon/economicsmocks/economicsHandlerMock.go b/testscommon/economicsmocks/economicsHandlerMock.go index 0c92fff0238..b1e4321f389 100644 --- a/testscommon/economicsmocks/economicsHandlerMock.go +++ b/testscommon/economicsmocks/economicsHandlerMock.go @@ -5,7 +5,6 @@ import ( "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/data" - "github.com/multiversx/mx-chain-go/process" ) // EconomicsHandlerMock - @@ -48,8 +47,6 @@ type EconomicsHandlerMock struct { ComputeGasLimitInEpochCalled func(tx data.TransactionWithFeeHandler, epoch uint32) uint64 ComputeGasUsedAndFeeBasedOnRefundValueInEpochCalled func(tx data.TransactionWithFeeHandler, refundValue *big.Int, epoch uint32) (uint64, *big.Int) ComputeTxFeeBasedOnGasUsedInEpochCalled func(tx data.TransactionWithFeeHandler, gasUsed uint64, epoch uint32) *big.Int - ComputeRelayedTxFeesCalled func(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) - SetTxTypeHandlerCalled func(txTypeHandler process.TxTypeHandler) error } // LeaderPercentage - @@ -346,22 +343,6 @@ func (ehm *EconomicsHandlerMock) ComputeTxFeeBasedOnGasUsedInEpoch(tx data.Trans return nil } -// ComputeRelayedTxFees - -func (ehm *EconomicsHandlerMock) ComputeRelayedTxFees(tx data.TransactionWithFeeHandler) (*big.Int, *big.Int, error) { - if ehm.ComputeRelayedTxFeesCalled != nil { - return ehm.ComputeRelayedTxFeesCalled(tx) - } - return big.NewInt(0), big.NewInt(0), nil -} - -// SetTxTypeHandler - -func (ehm *EconomicsHandlerMock) SetTxTypeHandler(txTypeHandler process.TxTypeHandler) error { - if ehm.SetTxTypeHandlerCalled != nil { - return ehm.SetTxTypeHandlerCalled(txTypeHandler) - } - return nil -} - // IsInterfaceNil returns true if there is no value under the interface func (ehm *EconomicsHandlerMock) IsInterfaceNil() bool { return ehm == nil diff --git a/testscommon/processMocks/failedTxLogsAccumulatorMock.go b/testscommon/processMocks/failedTxLogsAccumulatorMock.go deleted file mode 100644 index 903e56cd79f..00000000000 --- a/testscommon/processMocks/failedTxLogsAccumulatorMock.go +++ /dev/null @@ -1,41 +0,0 @@ -package processMocks - -import ( - "github.com/multiversx/mx-chain-core-go/data" - vmcommon "github.com/multiversx/mx-chain-vm-common-go" -) - -// FailedTxLogsAccumulatorMock - -type FailedTxLogsAccumulatorMock struct { - GetLogsCalled func(txHash []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) - SaveLogsCalled func(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error - RemoveCalled func(txHash []byte) -} - -// GetLogs - -func (mock *FailedTxLogsAccumulatorMock) GetLogs(txHash []byte) (data.TransactionHandler, []*vmcommon.LogEntry, bool) { - if mock.GetLogsCalled != nil { - return mock.GetLogsCalled(txHash) - } - return nil, nil, false -} - -// SaveLogs - -func (mock *FailedTxLogsAccumulatorMock) SaveLogs(txHash []byte, tx data.TransactionHandler, logs []*vmcommon.LogEntry) error { - if mock.SaveLogsCalled != nil { - return mock.SaveLogsCalled(txHash, tx, logs) - } - return nil -} - -// Remove - -func (mock *FailedTxLogsAccumulatorMock) Remove(txHash []byte) { - if mock.RemoveCalled != nil { - mock.RemoveCalled(txHash) - } -} - -// IsInterfaceNil - -func (mock *FailedTxLogsAccumulatorMock) IsInterfaceNil() bool { - return mock == nil -} diff --git a/testscommon/processMocks/relayedTxV3ProcessorMock.go b/testscommon/processMocks/relayedTxV3ProcessorMock.go deleted file mode 100644 index 85af9584af5..00000000000 --- a/testscommon/processMocks/relayedTxV3ProcessorMock.go +++ /dev/null @@ -1,23 +0,0 @@ -package processMocks - -import ( - "github.com/multiversx/mx-chain-core-go/data/transaction" -) - -// RelayedTxV3ProcessorMock - -type RelayedTxV3ProcessorMock struct { - CheckRelayedTxCalled func(tx *transaction.Transaction) error -} - -// CheckRelayedTx - -func (mock *RelayedTxV3ProcessorMock) CheckRelayedTx(tx *transaction.Transaction) error { - if mock.CheckRelayedTxCalled != nil { - return mock.CheckRelayedTxCalled(tx) - } - return nil -} - -// IsInterfaceNil - -func (mock *RelayedTxV3ProcessorMock) IsInterfaceNil() bool { - return mock == nil -} diff --git a/update/factory/exportHandlerFactory.go b/update/factory/exportHandlerFactory.go index a8ed95f4ceb..c13f25f3f5a 100644 --- a/update/factory/exportHandlerFactory.go +++ b/update/factory/exportHandlerFactory.go @@ -18,7 +18,6 @@ import ( mxFactory "github.com/multiversx/mx-chain-go/factory" "github.com/multiversx/mx-chain-go/genesis/process/disabled" "github.com/multiversx/mx-chain-go/process" - processDisabled "github.com/multiversx/mx-chain-go/process/disabled" "github.com/multiversx/mx-chain-go/sharding" "github.com/multiversx/mx-chain-go/sharding/nodesCoordinator" "github.com/multiversx/mx-chain-go/state" @@ -589,7 +588,6 @@ func (e *exportHandlerFactory) createInterceptors() error { FullArchiveInterceptorsContainer: e.fullArchiveInterceptorsContainer, AntifloodHandler: e.networkComponents.InputAntiFloodHandler(), NodeOperationMode: e.nodeOperationMode, - RelayedTxV3Processor: processDisabled.NewRelayedTxV3Processor(), } fullSyncInterceptors, err := NewFullSyncInterceptorsContainerFactory(argsInterceptors) if err != nil { diff --git a/update/factory/fullSyncInterceptors.go b/update/factory/fullSyncInterceptors.go index 67d5a86a503..0fe0298c4d6 100644 --- a/update/factory/fullSyncInterceptors.go +++ b/update/factory/fullSyncInterceptors.go @@ -75,7 +75,6 @@ type ArgsNewFullSyncInterceptorsContainerFactory struct { FullArchiveInterceptorsContainer process.InterceptorsContainer AntifloodHandler process.P2PAntifloodHandler NodeOperationMode common.NodeOperation - RelayedTxV3Processor process.RelayedTxV3Processor } // NewFullSyncInterceptorsContainerFactory is responsible for creating a new interceptors factory object @@ -146,7 +145,6 @@ func NewFullSyncInterceptorsContainerFactory( EpochStartTrigger: args.EpochStartTrigger, WhiteListerVerifiedTxs: args.WhiteListerVerifiedTxs, ArgsParser: smartContract.NewArgumentParser(), - RelayedTxV3Processor: args.RelayedTxV3Processor, } icf := &fullSyncInterceptorsContainerFactory{ From 0678c6eb479d913087a82e61e71dd274f1735119 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Oct 2024 08:50:26 +0300 Subject: [PATCH 02/13] updated indexer --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 8718f3e9d10..b1eb1aa4ddb 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,7 @@ require ( github.com/multiversx/mx-chain-communication-go v1.1.0 github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c github.com/multiversx/mx-chain-crypto-go v1.2.12 - github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6 + github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018130218-f48c7282690b github.com/multiversx/mx-chain-logger-go v1.0.15 github.com/multiversx/mx-chain-scenario-go v1.4.4 github.com/multiversx/mx-chain-storage-go v1.0.16 diff --git a/go.sum b/go.sum index 232f91ed5a7..32ad88ef7af 100644 --- a/go.sum +++ b/go.sum @@ -391,8 +391,8 @@ github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c h1: github.com/multiversx/mx-chain-core-go v1.2.23-0.20241018134424-75bab2a9058c/go.mod h1:B5zU4MFyJezmEzCsAHE9YNULmGCm2zbPHvl9hazNxmE= github.com/multiversx/mx-chain-crypto-go v1.2.12 h1:zWip7rpUS4CGthJxfKn5MZfMfYPjVjIiCID6uX5BSOk= github.com/multiversx/mx-chain-crypto-go v1.2.12/go.mod h1:HzcPpCm1zanNct/6h2rIh+MFrlXbjA5C8+uMyXj3LI4= -github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6 h1:2F5WyCIvFVs4CONd9kJxibY1NIfJLYFAwqNJvC31qNA= -github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018153953-b27532a1b4a6/go.mod h1:AJew7KVcICVyVDlXpDQzvjcSnKs0aCYl7eXnJwg+15E= +github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018130218-f48c7282690b h1:GYvm0yGkdQ3OCfNqnyIQNzAzydN3cES8noJZ3eZHN1A= +github.com/multiversx/mx-chain-es-indexer-go v1.7.10-0.20241018130218-f48c7282690b/go.mod h1:oGcRK2E3Syv6vRTszWrrb/TqD8akq0yeoMr1wPPiTO4= github.com/multiversx/mx-chain-logger-go v1.0.15 h1:HlNdK8etyJyL9NQ+6mIXyKPEBo+wRqOwi3n+m2QIHXc= github.com/multiversx/mx-chain-logger-go v1.0.15/go.mod h1:t3PRKaWB1M+i6gUfD27KXgzLJJC+mAQiN+FLlL1yoGQ= github.com/multiversx/mx-chain-scenario-go v1.4.4 h1:DVE2V+FPeyD/yWoC+KEfPK3jsFzHeruelESfpTlf460= From 953bb39d3627e20276876a66a966676e18556766 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Oct 2024 10:54:07 +0300 Subject: [PATCH 03/13] possible fix for failing test --- factory/processing/txSimulatorProcessComponents_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/factory/processing/txSimulatorProcessComponents_test.go b/factory/processing/txSimulatorProcessComponents_test.go index aad848600d8..0c919b0ba95 100644 --- a/factory/processing/txSimulatorProcessComponents_test.go +++ b/factory/processing/txSimulatorProcessComponents_test.go @@ -9,6 +9,7 @@ import ( "github.com/multiversx/mx-chain-go/process/mock" "github.com/multiversx/mx-chain-go/testscommon/components" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { @@ -40,6 +41,7 @@ func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { assert.Nil(t, err) assert.False(t, check.IfNil(apiTransactionEvaluator)) assert.False(t, check.IfNil(vmContainerFactory)) + require.NoError(t, vmContainerFactory.Close()) }) t.Run("should work for metachain", func(t *testing.T) { processArgs := components.GetProcessComponentsFactoryArgs(shardCoordinatorForMetachain) @@ -49,5 +51,6 @@ func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { assert.Nil(t, err) assert.False(t, check.IfNil(apiTransactionEvaluator)) assert.False(t, check.IfNil(vmContainerFactory)) + require.NoError(t, vmContainerFactory.Close()) }) } From 919d287c618073636f8a3a636db5fcae9bc30b03 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Oct 2024 13:20:20 +0300 Subject: [PATCH 04/13] fixes after review --- node/external/dtos.go | 1 - node/external/transactionAPI/gasUsedAndFeeProcessor.go | 3 --- 2 files changed, 4 deletions(-) diff --git a/node/external/dtos.go b/node/external/dtos.go index ad8d073967b..f884d8d32c9 100644 --- a/node/external/dtos.go +++ b/node/external/dtos.go @@ -17,5 +17,4 @@ type ArgsCreateTransaction struct { Options uint32 Guardian string GuardianSigHex string - Relayer string } diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor.go b/node/external/transactionAPI/gasUsedAndFeeProcessor.go index ab5c77fee40..bc01297ef85 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor.go @@ -62,9 +62,6 @@ func (gfp *gasUsedAndFeeProcessor) computeAndAttachGasUsedAndFee(tx *transaction if !scr.IsRefund || scr.RcvAddr != tx.Sender { continue } - if scr.RcvAddr != tx.Sender { - continue - } gfp.setGasUsedAndFeeBaseOnRefundValue(tx, scr.Value) hasRefundForSender = true From 2bcbc152fd4075631d12d070e093b119957d4b0c Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Oct 2024 14:12:47 +0300 Subject: [PATCH 05/13] removed config --- cmd/node/config/config.toml | 3 --- config/config.go | 7 ------- testscommon/generalConfig.go | 3 --- 3 files changed, 13 deletions(-) diff --git a/cmd/node/config/config.toml b/cmd/node/config/config.toml index 7f07d4dd380..6e1205d5f7e 100644 --- a/cmd/node/config/config.toml +++ b/cmd/node/config/config.toml @@ -946,6 +946,3 @@ # MaxRoundsOfInactivityAccepted defines the number of rounds missed by a main or higher level backup machine before # the current machine will take over and propose/sign blocks. Used in both single-key and multi-key modes. MaxRoundsOfInactivityAccepted = 3 - -[RelayedTransactionConfig] - MaxTransactionsAllowed = 50 diff --git a/config/config.go b/config/config.go index 412ab59f776..49ef257c341 100644 --- a/config/config.go +++ b/config/config.go @@ -228,8 +228,6 @@ type Config struct { PeersRatingConfig PeersRatingConfig PoolsCleanersConfig PoolsCleanersConfig Redundancy RedundancyConfig - - RelayedTransactionConfig RelayedTransactionConfig } // PeersRatingConfig will hold settings related to peers rating @@ -642,8 +640,3 @@ type PoolsCleanersConfig struct { type RedundancyConfig struct { MaxRoundsOfInactivityAccepted int } - -// RelayedTransactionConfig represents the config options to be used for relayed transactions -type RelayedTransactionConfig struct { - MaxTransactionsAllowed int -} diff --git a/testscommon/generalConfig.go b/testscommon/generalConfig.go index 53299443ebe..1eea96a2bdb 100644 --- a/testscommon/generalConfig.go +++ b/testscommon/generalConfig.go @@ -429,9 +429,6 @@ func GetGeneralConfig() config.Config { ResourceStats: config.ResourceStatsConfig{ RefreshIntervalInSec: 1, }, - RelayedTransactionConfig: config.RelayedTransactionConfig{ - MaxTransactionsAllowed: 10, - }, } } From 520f93f7db12bd54c49a670ed49d193830e8a52e Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Oct 2024 15:47:40 +0300 Subject: [PATCH 06/13] more fixes after review --- config/tomlConfig_test.go | 24 +++++++++---------- .../multiShard/relayedTx/common.go | 6 ++--- .../multiShard/relayedTx/relayedTx_test.go | 12 +++++----- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/config/tomlConfig_test.go b/config/tomlConfig_test.go index e7095b0b096..39a582b1ef2 100644 --- a/config/tomlConfig_test.go +++ b/config/tomlConfig_test.go @@ -867,22 +867,22 @@ func TestEnableEpochConfig(t *testing.T) { UseGasBoundedShouldFailExecutionEnableEpoch = 96 # DynamicESDTEnableEpoch represents the epoch when dynamic NFT feature is enabled - DynamicESDTEnableEpoch = 96 + DynamicESDTEnableEpoch = 97 # EGLDInMultiTransferEnableEpoch represents the epoch when EGLD in MultiTransfer is enabled - EGLDInMultiTransferEnableEpoch = 97 + EGLDInMultiTransferEnableEpoch = 98 # CryptoOpcodesV2EnableEpoch represents the epoch when BLSMultiSig, Secp256r1 and other opcodes are enabled - CryptoOpcodesV2EnableEpoch = 98 + CryptoOpcodesV2EnableEpoch = 99 # FixRelayedBaseCostEnableEpoch represents the epoch when the fix for relayed base cost will be enabled - FixRelayedBaseCostEnableEpoch = 99 + FixRelayedBaseCostEnableEpoch = 100 # MultiESDTNFTTransferAndExecuteByUserEnableEpoch represents the epoch when enshrined sovereign cross chain opcodes are enabled - MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 100 + MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 101 # FixRelayedMoveBalanceToNonPayableSCEnableEpoch represents the epoch when the fix for relayed move balance to non payable sc will be enabled - FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 101 + FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 102 # MaxNodesChangeEnableEpoch holds configuration for changing the maximum number of nodes and the enabling epoch MaxNodesChangeEnableEpoch = [ @@ -998,12 +998,12 @@ func TestEnableEpochConfig(t *testing.T) { AlwaysMergeContextsInEEIEnableEpoch: 94, CleanupAuctionOnLowWaitingListEnableEpoch: 95, UseGasBoundedShouldFailExecutionEnableEpoch: 96, - DynamicESDTEnableEpoch: 96, - EGLDInMultiTransferEnableEpoch: 97, - CryptoOpcodesV2EnableEpoch: 98, - FixRelayedBaseCostEnableEpoch: 99, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 100, - FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 101, + DynamicESDTEnableEpoch: 97, + EGLDInMultiTransferEnableEpoch: 98, + CryptoOpcodesV2EnableEpoch: 99, + FixRelayedBaseCostEnableEpoch: 100, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 101, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 102, MaxNodesChangeEnableEpoch: []MaxNodesChangeConfig{ { EpochEnable: 44, diff --git a/integrationTests/multiShard/relayedTx/common.go b/integrationTests/multiShard/relayedTx/common.go index 54d99ff869d..a9098c6c668 100644 --- a/integrationTests/multiShard/relayedTx/common.go +++ b/integrationTests/multiShard/relayedTx/common.go @@ -15,16 +15,16 @@ import ( ) // CreateGeneralSetupForRelayTxTest will create the general setup for relayed transactions -func CreateGeneralSetupForRelayTxTest(relayedV3Test bool) ([]*integrationTests.TestProcessorNode, []int, []*integrationTests.TestWalletAccount, *integrationTests.TestWalletAccount) { +func CreateGeneralSetupForRelayTxTest(baseCostFixEnabled bool) ([]*integrationTests.TestProcessorNode, []int, []*integrationTests.TestWalletAccount, *integrationTests.TestWalletAccount) { initialVal := big.NewInt(10000000000) epochsConfig := integrationTests.GetDefaultEnableEpochsConfig() - if !relayedV3Test { + if !baseCostFixEnabled { epochsConfig.FixRelayedBaseCostEnableEpoch = integrationTests.UnreachableEpoch epochsConfig.FixRelayedMoveBalanceToNonPayableSCEnableEpoch = integrationTests.UnreachableEpoch } nodes, idxProposers := createAndMintNodes(initialVal, epochsConfig) - players, relayerAccount := createAndMintPlayers(relayedV3Test, nodes, initialVal) + players, relayerAccount := createAndMintPlayers(baseCostFixEnabled, nodes, initialVal) return nodes, idxProposers, players, relayerAccount } diff --git a/integrationTests/multiShard/relayedTx/relayedTx_test.go b/integrationTests/multiShard/relayedTx/relayedTx_test.go index 87a54633953..41ece5b81eb 100644 --- a/integrationTests/multiShard/relayedTx/relayedTx_test.go +++ b/integrationTests/multiShard/relayedTx/relayedTx_test.go @@ -51,14 +51,14 @@ func TestRelayedTransactionInMultiShardEnvironmentWithAttestationContract(t *tes func testRelayedTransactionInMultiShardEnvironmentWithNormalTx( createAndSendRelayedAndUserTxFunc createAndSendRelayedAndUserTxFuncType, - relayedV3Test bool, + baseCostFixEnabled bool, ) func(t *testing.T) { return func(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") } - nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(relayedV3Test) + nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(baseCostFixEnabled) defer func() { for _, n := range nodes { n.Close() @@ -115,14 +115,14 @@ func testRelayedTransactionInMultiShardEnvironmentWithNormalTx( func testRelayedTransactionInMultiShardEnvironmentWithSmartContractTX( createAndSendRelayedAndUserTxFunc createAndSendRelayedAndUserTxFuncType, - relayedV3Test bool, + baseCostFixEnabled bool, ) func(t *testing.T) { return func(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") } - nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(relayedV3Test) + nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(baseCostFixEnabled) defer func() { for _, n := range nodes { n.Close() @@ -211,14 +211,14 @@ func testRelayedTransactionInMultiShardEnvironmentWithSmartContractTX( func testRelayedTransactionInMultiShardEnvironmentWithESDTTX( createAndSendRelayedAndUserTxFunc createAndSendRelayedAndUserTxFuncType, - relayedV3Test bool, + baseCostFixEnabled bool, ) func(t *testing.T) { return func(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") } - nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(relayedV3Test) + nodes, idxProposers, players, relayer := CreateGeneralSetupForRelayTxTest(baseCostFixEnabled) defer func() { for _, n := range nodes { n.Close() From 5897fbc85dc57227b1b3ebd714d810ad577de881 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Tue, 22 Oct 2024 12:12:16 +0300 Subject: [PATCH 07/13] fix for workflow --- .../build_and_run_chain_simulator_and_execute_system_test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml b/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml index f766ccddbf5..8cf5c879345 100644 --- a/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml +++ b/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml @@ -164,7 +164,7 @@ jobs: - name: Run tests and generate HTML report run: | set +e - pytest mx-chain-testing-suite/scenarios/ --html=report.html --self-contained-html --continue-on-collection-errors + pytest --html=report.html --self-contained-html --continue-on-collection-errors PYTEST_EXIT_CODE=$? set -e echo "PYTEST_EXIT_CODE=$PYTEST_EXIT_CODE" >> $GITHUB_ENV From 0b88dd59484f856aac69f3b37d6efb677958540f Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Tue, 22 Oct 2024 13:19:09 +0300 Subject: [PATCH 08/13] reverted last commit --- .../build_and_run_chain_simulator_and_execute_system_test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml b/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml index 8cf5c879345..f766ccddbf5 100644 --- a/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml +++ b/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml @@ -164,7 +164,7 @@ jobs: - name: Run tests and generate HTML report run: | set +e - pytest --html=report.html --self-contained-html --continue-on-collection-errors + pytest mx-chain-testing-suite/scenarios/ --html=report.html --self-contained-html --continue-on-collection-errors PYTEST_EXIT_CODE=$? set -e echo "PYTEST_EXIT_CODE=$PYTEST_EXIT_CODE" >> $GITHUB_ENV From f8f6b35b3a0c04ad10f835baf0c0f27480953867 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Wed, 23 Oct 2024 21:57:41 +0300 Subject: [PATCH 09/13] fix gasUsed and fee for relayed v1 and v2 --- .../transactionAPI/apiTransactionProcessor.go | 2 +- .../transactionAPI/gasUsedAndFeeProcessor.go | 80 ++++++--- .../gasUsedAndFeeProcessor_test.go | 48 ++++++ .../relayedV1CreateNewDelegationContract.json | 158 ++++++++++++++++++ .../transactionsFeeProcessor.go | 46 +++-- 5 files changed, 295 insertions(+), 39 deletions(-) create mode 100644 node/external/transactionAPI/testData/relayedV1CreateNewDelegationContract.json diff --git a/node/external/transactionAPI/apiTransactionProcessor.go b/node/external/transactionAPI/apiTransactionProcessor.go index c4e75bc29b9..c67ad1cb445 100644 --- a/node/external/transactionAPI/apiTransactionProcessor.go +++ b/node/external/transactionAPI/apiTransactionProcessor.go @@ -201,7 +201,7 @@ func (atp *apiTransactionProcessor) populateComputedFieldInitiallyPaidFee(tx *tr isFeeFixActive := atp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) isRelayedAfterFix := tx.IsRelayed && isFeeFixActive if isRelayedAfterFix { - fee, _ = atp.gasUsedAndFeeProcessor.getFeeOfRelayed(tx) + _, fee, _ = atp.gasUsedAndFeeProcessor.getFeeOfRelayed(tx) tx.InitiallyPaidFee = fee.String() } } diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor.go b/node/external/transactionAPI/gasUsedAndFeeProcessor.go index bc01297ef85..06c2c7d3bfc 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor.go @@ -4,6 +4,7 @@ import ( "math/big" "github.com/multiversx/mx-chain-core-go/core" + "github.com/multiversx/mx-chain-core-go/core/check" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-core-go/marshal" "github.com/multiversx/mx-chain-go/common" @@ -49,7 +50,7 @@ func (gfp *gasUsedAndFeeProcessor) computeAndAttachGasUsedAndFee(tx *transaction tx.Fee = tx.InitiallyPaidFee } - initialTotalFee, isRelayed := gfp.getFeeOfRelayed(tx) + userTx, initialTotalFee, isRelayed := gfp.getFeeOfRelayed(tx) isRelayedAfterFix := isRelayed && isFeeFixActive if isRelayedAfterFix { tx.InitiallyPaidFee = initialTotalFee.String() @@ -63,26 +64,26 @@ func (gfp *gasUsedAndFeeProcessor) computeAndAttachGasUsedAndFee(tx *transaction continue } - gfp.setGasUsedAndFeeBaseOnRefundValue(tx, scr.Value) + gfp.setGasUsedAndFeeBaseOnRefundValue(tx, userTx, scr.Value) hasRefundForSender = true break } - gfp.prepareTxWithResultsBasedOnLogs(tx, hasRefundForSender) + gfp.prepareTxWithResultsBasedOnLogs(tx, userTx, hasRefundForSender) } -func (gfp *gasUsedAndFeeProcessor) getFeeOfRelayed(tx *transaction.ApiTransactionResult) (*big.Int, bool) { +func (gfp *gasUsedAndFeeProcessor) getFeeOfRelayed(tx *transaction.ApiTransactionResult) (*transaction.ApiTransactionResult, *big.Int, bool) { if !tx.IsRelayed { - return nil, false + return nil, nil, false } if len(tx.Data) == 0 { - return nil, false + return nil, nil, false } funcName, args, err := gfp.argsParser.ParseCallData(string(tx.Data)) if err != nil { - return nil, false + return nil, nil, false } if funcName == core.RelayedTransaction { @@ -93,32 +94,33 @@ func (gfp *gasUsedAndFeeProcessor) getFeeOfRelayed(tx *transaction.ApiTransactio return gfp.handleRelayedV2(args, tx) } - return nil, false + return nil, nil, false } -func (gfp *gasUsedAndFeeProcessor) handleRelayedV1(args [][]byte, tx *transaction.ApiTransactionResult) (*big.Int, bool) { +func (gfp *gasUsedAndFeeProcessor) handleRelayedV1(args [][]byte, tx *transaction.ApiTransactionResult) (*transaction.ApiTransactionResult, *big.Int, bool) { if len(args) != 1 { - return nil, false + return nil, nil, false } innerTx := &transaction.Transaction{} err := gfp.marshaller.Unmarshal(innerTx, args[0]) if err != nil { - return nil, false + return nil, nil, false } gasUsed := gfp.feeComputer.ComputeGasLimit(tx) fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsed) - innerFee := gfp.feeComputer.ComputeTransactionFee(&transaction.ApiTransactionResult{ + innerTxApiResult := &transaction.ApiTransactionResult{ Tx: innerTx, Epoch: tx.Epoch, - }) + } + innerFee := gfp.feeComputer.ComputeTransactionFee(innerTxApiResult) - return big.NewInt(0).Add(fee, innerFee), true + return innerTxApiResult, big.NewInt(0).Add(fee, innerFee), true } -func (gfp *gasUsedAndFeeProcessor) handleRelayedV2(args [][]byte, tx *transaction.ApiTransactionResult) (*big.Int, bool) { +func (gfp *gasUsedAndFeeProcessor) handleRelayedV2(args [][]byte, tx *transaction.ApiTransactionResult) (*transaction.ApiTransactionResult, *big.Int, bool) { innerTx := &transaction.Transaction{} innerTx.RcvAddr = args[0] innerTx.Nonce = big.NewInt(0).SetBytes(args[1]).Uint64() @@ -132,16 +134,18 @@ func (gfp *gasUsedAndFeeProcessor) handleRelayedV2(args [][]byte, tx *transactio gasUsed := gfp.feeComputer.ComputeGasLimit(tx) fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsed) - innerFee := gfp.feeComputer.ComputeTransactionFee(&transaction.ApiTransactionResult{ + innerTxApiResult := &transaction.ApiTransactionResult{ Tx: innerTx, Epoch: tx.Epoch, - }) + } + innerFee := gfp.feeComputer.ComputeTransactionFee(innerTxApiResult) - return big.NewInt(0).Add(fee, innerFee), true + return innerTxApiResult, big.NewInt(0).Add(fee, innerFee), true } func (gfp *gasUsedAndFeeProcessor) prepareTxWithResultsBasedOnLogs( tx *transaction.ApiTransactionResult, + userTx *transaction.ApiTransactionResult, hasRefund bool, ) { if tx.Logs == nil || (tx.Function == "" && tx.Operation == datafield.OperationTransfer) { @@ -149,15 +153,26 @@ func (gfp *gasUsedAndFeeProcessor) prepareTxWithResultsBasedOnLogs( } for _, event := range tx.Logs.Events { - gfp.setGasUsedAndFeeBaseOnLogEvent(tx, hasRefund, event) + gfp.setGasUsedAndFeeBaseOnLogEvent(tx, userTx, hasRefund, event) } } -func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnLogEvent(tx *transaction.ApiTransactionResult, hasRefund bool, event *transaction.Events) { +func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnLogEvent(tx *transaction.ApiTransactionResult, userTx *transaction.ApiTransactionResult, hasRefund bool, event *transaction.Events) { if core.WriteLogIdentifier == event.Identifier && !hasRefund { - gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, big.NewInt(0)) - tx.GasUsed = gasUsed - tx.Fee = fee.String() + if !check.IfNilReflect(userTx) && gfp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) { + gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, big.NewInt(0)) + gasUsedRelayedTx := gfp.feeComputer.ComputeGasLimit(tx) + feeRelayedTx := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) + + tx.GasUsed = gasUsed + gasUsedRelayedTx + + fee.Add(fee, feeRelayedTx) + tx.Fee = fee.String() + } else { + gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, big.NewInt(0)) + tx.GasUsed = gasUsed + tx.Fee = fee.String() + } } if core.SignalErrorOperation == event.Identifier { fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, tx.GasLimit) @@ -166,14 +181,29 @@ func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnLogEvent(tx *transactio } } -func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnRefundValue(tx *transaction.ApiTransactionResult, refund *big.Int) { +func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnRefundValue( + tx *transaction.ApiTransactionResult, + userTx *transaction.ApiTransactionResult, + refund *big.Int, +) { + if !check.IfNilReflect(userTx) && gfp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) { + gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, refund) + gasUsedRelayedTx := gfp.feeComputer.ComputeGasLimit(tx) + feeRelayedTx := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) + + tx.GasUsed = gasUsed + gasUsedRelayedTx + + fee.Add(fee, feeRelayedTx) + tx.Fee = fee.String() + + return + } gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, refund) tx.GasUsed = gasUsed tx.Fee = fee.String() - } func (gfp *gasUsedAndFeeProcessor) isESDTOperationWithSCCall(tx *transaction.ApiTransactionResult) bool { diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go index c6abd9278d6..8c5c80826c0 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go @@ -346,3 +346,51 @@ func TestComputeAndAttachGasUsedAndFeeFailedRelayedV1(t *testing.T) { require.Equal(t, "1198000000000000", txWithSRefundSCR.Fee) require.Equal(t, "1274230000000000", txWithSRefundSCR.InitiallyPaidFee) } + +func TestComputeAndAttachGasUsedAndFeeRelayedV1CreateNewDelegationContractWithRefund(t *testing.T) { + t.Parallel() + + enableEpochsHandler := &enableEpochsHandlerMock.EnableEpochsHandlerStub{ + IsFlagEnabledInEpochCalled: func(flag core.EnableEpochFlag, epoch uint32) bool { + return flag == common.GasPriceModifierFlag || + flag == common.PenalizedTooMuchGasFlag || + flag == common.FixRelayedBaseCostFlag + }, + } + feeComp, _ := fee.NewFeeComputer(createEconomicsData(enableEpochsHandler)) + computer := fee.NewTestFeeComputer(feeComp) + + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + smartContract.NewArgumentParser(), + &marshal.JsonMarshalizer{}, + enableEpochsHandler, + ) + + txWithSRefundSCR := &transaction.ApiTransactionResult{} + err := core.LoadJsonFile(txWithSRefundSCR, "testData/relayedV1CreateNewDelegationContract.json") + require.NoError(t, err) + + snd, _ := pubKeyConverter.Decode(txWithSRefundSCR.Sender) + rcv, _ := pubKeyConverter.Decode(txWithSRefundSCR.Receiver) + val, _ := big.NewInt(0).SetString(txWithSRefundSCR.Value, 10) + txWithSRefundSCR.Tx = &transaction.Transaction{ + Nonce: txWithSRefundSCR.Nonce, + Value: val, + RcvAddr: rcv, + SndAddr: snd, + GasPrice: txWithSRefundSCR.GasPrice, + GasLimit: txWithSRefundSCR.GasLimit, + Data: txWithSRefundSCR.Data, + } + + txWithSRefundSCR.InitiallyPaidFee = "" + txWithSRefundSCR.Fee = "" + txWithSRefundSCR.GasUsed = 0 + + gasUsedAndFeeProc.computeAndAttachGasUsedAndFee(txWithSRefundSCR) + require.Equal(t, uint64(56328500), txWithSRefundSCR.GasUsed) + require.Equal(t, "1878500000000000", txWithSRefundSCR.Fee) + require.Equal(t, "2177505000000000", txWithSRefundSCR.InitiallyPaidFee) +} diff --git a/node/external/transactionAPI/testData/relayedV1CreateNewDelegationContract.json b/node/external/transactionAPI/testData/relayedV1CreateNewDelegationContract.json new file mode 100644 index 00000000000..a15e3c533ae --- /dev/null +++ b/node/external/transactionAPI/testData/relayedV1CreateNewDelegationContract.json @@ -0,0 +1,158 @@ +{ + "type": "normal", + "processingTypeOnSource": "RelayedTx", + "processingTypeOnDestination": "RelayedTx", + "hash": "94cb3bd3e2dca9920115f05549c9eee4dfc1d33e4ac3edd0741eb51165148b52", + "nonce": 0, + "round": 7, + "epoch": 1, + "value": "0", + "receiver": "erd1s89rm6mv6xyct38r3vqadj74rmqunamhwyz7c84a6u9thedj2wus5nlchg", + "sender": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", + "gasPrice": 1000000000, + "gasLimit": 86229000, + "data": "cmVsYXllZFR4QDdiMjI2ZTZmNmU2MzY1MjIzYTMwMmMyMjczNjU2ZTY0NjU3MjIyM2EyMjY3NjM2ZjM5MzYzMjdhNTI2OTU5NTg0NTM0MzQ3MzQyMzE3Mzc2NTY0ODczNDg0YTM5MzM2NDc4NDI2NTc3NjU3NjY0NjM0Yjc1MmI1Nzc5NTUzNzZiM2QyMjJjMjI3MjY1NjM2NTY5NzY2NTcyMjIzYTIyNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE1MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDUyZjJmMzgzZDIyMmMyMjc2NjE2Yzc1NjUyMjNhMzIzNTMwMzEzMDMwMzAzMDMwMzAzMDMwMzAzMDMwMzAzMDMwMzAzMDMwMzAyYzIyNjc2MTczNTA3MjY5NjM2NTIyM2EzMTMwMzAzMDMwMzAzMDMwMzAzMDJjMjI2NzYxNzM0YzY5NmQ2OTc0MjIzYTM4MzUzMDMwMzAzMDMwMzAyYzIyNjQ2MTc0NjEyMjNhMjI1OTMzNGE2YzU5NTg1MjZjNTQ2ZDU2MzM1MjQ3NTY3MzVhNTc2NDY4NjQ0NzZjNzY2MjZiNGU3NjYyNmU1Mjc5NTk1NzRlMzA1MTQ0NDE3NzUxNDQ0MTc3MjIyYzIyNzM2OTY3NmU2MTc0NzU3MjY1MjIzYTIyNTk1MTUzNTQ0MjMwMzE0ZjUwNGY0NDU5MzM0ZDU2NDQ1NDRkNWE3NzRkNzY2NjZiNzI1MDUwMzk2ZTM1NjQ1MzU4NjI3MDQ5NWE2MjcwNDM1MTQ5MzMzNDRkNTY2NzZiNzYzMzc0Njk2MTRmNGMzNjQ0NWE2NjM4NTU2NTJmNjg2Zjc5MzkzNTRiNGI2NTVhNDI2YjcwNzAzMTU1NzY3NzU5MzY0NzU3NDI3NzNkM2QyMjJjMjI2MzY4NjE2OTZlNDk0NDIyM2EyMjU5MzI2ODY4NjE1NzM0M2QyMjJjMjI3NjY1NzI3MzY5NmY2ZTIyM2EzMjdk", + "signature": "bf5d14d237b951d23247e99113fa15566ebbd0dccd215b743ae9629f226ab3f9ba333622567c5606e2ed06104df52f81f05fad2488be9cb50a83e1356e0d070e", + "sourceShard": 1, + "destinationShard": 1, + "blockNonce": 7, + "blockHash": "5f2a597d07b4b5ae84195178eb6f83493bb1230c7f316b40a0d9b6efbe1a4da5", + "notarizedAtSourceInMetaNonce": 9, + "NotarizedAtSourceInMetaHash": "34cd7dc91fc9773ddd2e09d900087b96cfecf6280a6dc25a1894c2db161cded1", + "notarizedAtDestinationInMetaNonce": 9, + "notarizedAtDestinationInMetaHash": "34cd7dc91fc9773ddd2e09d900087b96cfecf6280a6dc25a1894c2db161cded1", + "miniblockType": "TxBlock", + "miniblockHash": "03ef037eb1fd03f89a9b5ece12aa422223b440cb1fd02c4a6b82d65268121d28", + "hyperblockNonce": 9, + "hyperblockHash": "34cd7dc91fc9773ddd2e09d900087b96cfecf6280a6dc25a1894c2db161cded1", + "timestamp": 1729691671, + "smartContractResults": [ + { + "hash": "6e71137c75ad162d97ce45502d38f0af96362c06f03378f03a4e50bec6ce31ea", + "nonce": 1, + "value": 299005000000000, + "receiver": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", + "sender": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", + "prevTxHash": "c825db2f9e6d17e41ed12e1aac86eecd7a828eeea0caf63a6e6a979f02a74f70", + "originalTxHash": "94cb3bd3e2dca9920115f05549c9eee4dfc1d33e4ac3edd0741eb51165148b52", + "gasLimit": 0, + "gasPrice": 1000000000, + "callType": 0, + "returnMessage": "gas refund for relayer", + "logs": { + "address": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", + "events": [ + { + "address": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", + "identifier": "completedTxEvent", + "topics": [ + "yCXbL55tF+Qe0S4arIbuzXqCju6gyvY6bmqXnwKnT3A=" + ], + "data": null, + "additionalData": null + } + ] + }, + "operation": "transfer", + "isRefund": true + }, + { + "hash": "c825db2f9e6d17e41ed12e1aac86eecd7a828eeea0caf63a6e6a979f02a74f70", + "nonce": 0, + "value": 2501000000000000000000, + "receiver": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", + "sender": "erd1s89rm6mv6xyct38r3vqadj74rmqunamhwyz7c84a6u9thedj2wus5nlchg", + "relayerAddress": "erd1tp66n2lkhs2fm7elvh9lmzfajpg480v55sd8lf2lvu4fw92zsrasvn2wze", + "relayedValue": 0, + "data": "createNewDelegationContract@00@00", + "prevTxHash": "94cb3bd3e2dca9920115f05549c9eee4dfc1d33e4ac3edd0741eb51165148b52", + "originalTxHash": "94cb3bd3e2dca9920115f05549c9eee4dfc1d33e4ac3edd0741eb51165148b52", + "gasLimit": 84900500, + "gasPrice": 1000000000, + "callType": 0, + "logs": { + "address": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", + "events": [ + { + "address": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", + "identifier": "transferValueOnly", + "topics": [ + "h5RY6SJT9AAA", + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAL///8=" + ], + "data": "RGVwbG95U21hcnRDb250cmFjdA==", + "additionalData": [ + "RGVwbG95U21hcnRDb250cmFjdA==", + "X2luaXQ=", + "AA==", + "AA==" + ] + }, + { + "address": "erd1s89rm6mv6xyct38r3vqadj74rmqunamhwyz7c84a6u9thedj2wus5nlchg", + "identifier": "delegate", + "topics": [ + "h5RY6SJT9AAA", + "h5RY6SJT9AAA", + "AQ==", + "h5RY6SJT9AAA", + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAL///8=" + ], + "data": null, + "additionalData": null + }, + { + "address": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqhllllsajxzat", + "identifier": "transferValueOnly", + "topics": [ + "h5RY6SJT9AAA", + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAB//8=" + ], + "data": "RXhlY3V0ZU9uRGVzdENvbnRleHQ=", + "additionalData": [ + "RXhlY3V0ZU9uRGVzdENvbnRleHQ=", + "c3Rha2U=" + ] + }, + { + "address": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqhllllsajxzat", + "identifier": "SCDeploy", + "topics": [ + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAL///8=", + "gco962zRiYXE44sB1svVHsHJ93dxBewevdcKu+WyU7k=", + "/uYNe6O98aIOSpF57HocNxS4JQ7FILx6+N7MEN3oAQY=" + ], + "data": null, + "additionalData": null + }, + { + "address": "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", + "identifier": "writeLog", + "topics": [ + "gco962zRiYXE44sB1svVHsHJ93dxBewevdcKu+WyU7k=" + ], + "data": "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMmZmZmZmZg==", + "additionalData": [ + "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMmZmZmZmZg==" + ] + } + ] + }, + "operation": "transfer", + "function": "createNewDelegationContract" + } + ], + "status": "success", + "receivers": [ + "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6" + ], + "receiversShardIDs": [ + 4294967295 + ], + "operation": "transfer", + "function": "createNewDelegationContract", + "isRelayed": true, + "chainID": "chain", + "version": 2, + "options": 0 +} diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index e0d56acbde3..ae59d6454d7 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -6,6 +6,7 @@ import ( "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/core/check" + "github.com/multiversx/mx-chain-core-go/data" outportcore "github.com/multiversx/mx-chain-core-go/data/outport" "github.com/multiversx/mx-chain-core-go/data/smartContractResult" "github.com/multiversx/mx-chain-core-go/data/transaction" @@ -135,7 +136,7 @@ func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *trans feeInfo.SetFee(initialPaidFee) } - totalFee, isRelayed := tep.getFeeOfRelayed(txWithResult) + userTx, totalFee, isRelayed := tep.getFeeOfRelayed(txWithResult) isRelayedAfterFix := isRelayed && isFeeFixActive if isRelayedAfterFix { feeInfo.SetFee(totalFee) @@ -144,11 +145,16 @@ func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *trans } - tep.prepareTxWithResults(txHashHex, txWithResult, isRelayedAfterFix) + tep.prepareTxWithResults(txHashHex, txWithResult, userTx, epoch) } } -func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWithResults *transactionWithResults, isRelayedAfterFix bool) { +func (tep *transactionsFeeProcessor) prepareTxWithResults( + txHashHex string, + txWithResults *transactionWithResults, + userTx data.TransactionHandler, + epoch uint32, +) { hasRefund := false for _, scrHandler := range txWithResults.scrs { scr, ok := scrHandler.GetTxHandler().(*smartContractResult.SmartContractResult) @@ -157,6 +163,20 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWi } if isSCRForSenderWithRefund(scr, txHashHex, txWithResults.GetTxHandler()) || isRefundForRelayed(scr, txWithResults.GetTxHandler()) { + if !check.IfNilReflect(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, scr.Value) + + tx := txWithResults.GetTxHandler() + gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) + feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) + + txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) + txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) + hasRefund = true + + break + } + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), scr.Value) txWithResults.GetFeeInfo().SetGasUsed(gasUsed) @@ -169,14 +189,14 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWi tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefund) } -func (tep *transactionsFeeProcessor) getFeeOfRelayed(tx *transactionWithResults) (*big.Int, bool) { +func (tep *transactionsFeeProcessor) getFeeOfRelayed(tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { if len(tx.GetTxHandler().GetData()) == 0 { - return nil, false + return nil, nil, false } funcName, args, err := tep.argsParser.ParseCallData(string(tx.GetTxHandler().GetData())) if err != nil { - return nil, false + return nil, nil, false } if funcName == core.RelayedTransaction { @@ -187,18 +207,18 @@ func (tep *transactionsFeeProcessor) getFeeOfRelayed(tx *transactionWithResults) return tep.handleRelayedV2(args, tx) } - return nil, false + return nil, nil, false } -func (tep *transactionsFeeProcessor) handleRelayedV1(args [][]byte, tx *transactionWithResults) (*big.Int, bool) { +func (tep *transactionsFeeProcessor) handleRelayedV1(args [][]byte, tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { if len(args) != 1 { - return nil, false + return nil, nil, false } innerTx := &transaction.Transaction{} err := tep.marshaller.Unmarshal(innerTx, args[0]) if err != nil { - return nil, false + return nil, nil, false } txHandler := tx.GetTxHandler() @@ -207,10 +227,10 @@ func (tep *transactionsFeeProcessor) handleRelayedV1(args [][]byte, tx *transact innerFee := tep.txFeeCalculator.ComputeTxFee(innerTx) - return big.NewInt(0).Add(fee, innerFee), true + return innerTx, big.NewInt(0).Add(fee, innerFee), true } -func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transactionWithResults) (*big.Int, bool) { +func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { txHandler := tx.GetTxHandler() innerTx := &transaction.Transaction{} @@ -228,7 +248,7 @@ func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transact innerFee := tep.txFeeCalculator.ComputeTxFee(innerTx) - return big.NewInt(0).Add(fee, innerFee), true + return innerTx, big.NewInt(0).Add(fee, innerFee), true } func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( From 79e9f2cc236d69ff789cd7a39b28829d9460b696 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Thu, 24 Oct 2024 09:06:06 +0300 Subject: [PATCH 10/13] fixed also prepareTxWithResultsBasedOnLogs --- .../transactionsfee/transactionsFeeProcessor.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index ae59d6454d7..f1d60d0034d 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -186,7 +186,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults( } } - tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefund) + tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, userTx, hasRefund, epoch) } func (tep *transactionsFeeProcessor) getFeeOfRelayed(tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { @@ -254,7 +254,9 @@ func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transact func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( txHashHex string, txWithResults *transactionWithResults, + userTx data.TransactionHandler, hasRefund bool, + epoch uint32, ) { tx := txWithResults.GetTxHandler() if check.IfNil(tx) { @@ -269,6 +271,19 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( for _, event := range txWithResults.log.GetLogEvents() { if core.WriteLogIdentifier == string(event.GetIdentifier()) && !hasRefund { + if !check.IfNilReflect(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, big.NewInt(0)) + + gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) + feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) + + txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) + txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) + hasRefund = true + + break + } + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), big.NewInt(0)) txWithResults.GetFeeInfo().SetGasUsed(gasUsed) txWithResults.GetFeeInfo().SetFee(fee) From 158ca36cdc80fe47ead80ec41663c2a0b362ea1b Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Thu, 24 Oct 2024 10:02:14 +0300 Subject: [PATCH 11/13] fixes after review --- .../transactionsFeeProcessor.go | 62 +++++++++++++++++-- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index f1d60d0034d..d94b83694bb 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -163,7 +163,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults( } if isSCRForSenderWithRefund(scr, txHashHex, txWithResults.GetTxHandler()) || isRefundForRelayed(scr, txWithResults.GetTxHandler()) { - if !check.IfNilReflect(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { + if !check.IfNil(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, scr.Value) tx := txWithResults.GetTxHandler() @@ -271,7 +271,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( for _, event := range txWithResults.log.GetLogEvents() { if core.WriteLogIdentifier == string(event.GetIdentifier()) && !hasRefund { - if !check.IfNilReflect(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { + if !check.IfNil(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, big.NewInt(0)) gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) @@ -326,10 +326,62 @@ func (tep *transactionsFeeProcessor) prepareScrsNoTx(transactionsAndScrs *transa continue } - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txFromStorage, scr.Value) + userTx := tep.getUserTxOfRelayed(txFromStorage) + if check.IfNil(userTx) { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txFromStorage, scr.Value) - scrHandler.GetFeeInfo().SetGasUsed(gasUsed) - scrHandler.GetFeeInfo().SetFee(fee) + scrHandler.GetFeeInfo().SetGasUsed(gasUsed) + scrHandler.GetFeeInfo().SetFee(fee) + } else { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, scr.Value) + + gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(txFromStorage) + feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(txFromStorage, gasUsedRelayedTx) + + scrHandler.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) + scrHandler.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) + } + } + + return nil +} + +func (tep *transactionsFeeProcessor) getUserTxOfRelayed(tx data.TransactionHandler) data.TransactionHandler { + if len(tx.GetData()) == 0 { + return nil + } + + funcName, args, err := tep.argsParser.ParseCallData(string(tx.GetData())) + if err != nil { + return nil + } + + if funcName == core.RelayedTransaction { + if len(args) != 1 { + return nil + } + + userTx := &transaction.Transaction{} + err := tep.marshaller.Unmarshal(userTx, args[0]) + if err != nil { + return nil + } + + return userTx + } + + if funcName == core.RelayedTransactionV2 { + userTx := &transaction.Transaction{} + userTx.RcvAddr = args[0] + userTx.Nonce = big.NewInt(0).SetBytes(args[1]).Uint64() + userTx.Data = args[2] + userTx.Signature = args[3] + userTx.Value = big.NewInt(0) + userTx.GasPrice = tx.GetGasPrice() + userTx.GasLimit = tx.GetGasLimit() - tep.txFeeCalculator.ComputeGasLimit(tx) + userTx.SndAddr = tx.GetRcvAddr() + + return userTx } return nil From 6f7ae0b36182ac3177b5e4fe1d8ba89178fb96ed Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Thu, 24 Oct 2024 11:53:56 +0300 Subject: [PATCH 12/13] fix linter --- outport/process/transactionsfee/transactionsFeeProcessor.go | 1 - 1 file changed, 1 deletion(-) diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index d94b83694bb..f66ffd3f9cf 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -279,7 +279,6 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) - hasRefund = true break } From 895c6b2922bdfa8b18ed62903d75807bb76064a3 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Thu, 24 Oct 2024 15:40:57 +0300 Subject: [PATCH 13/13] fixes after review, removed duplicated code --- .../transactionAPI/gasUsedAndFeeProcessor.go | 15 +---- .../transactionsFeeProcessor.go | 59 ++++++++----------- 2 files changed, 26 insertions(+), 48 deletions(-) diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor.go b/node/external/transactionAPI/gasUsedAndFeeProcessor.go index 06c2c7d3bfc..c4cd9578394 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor.go @@ -159,20 +159,7 @@ func (gfp *gasUsedAndFeeProcessor) prepareTxWithResultsBasedOnLogs( func (gfp *gasUsedAndFeeProcessor) setGasUsedAndFeeBaseOnLogEvent(tx *transaction.ApiTransactionResult, userTx *transaction.ApiTransactionResult, hasRefund bool, event *transaction.Events) { if core.WriteLogIdentifier == event.Identifier && !hasRefund { - if !check.IfNilReflect(userTx) && gfp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) { - gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, big.NewInt(0)) - gasUsedRelayedTx := gfp.feeComputer.ComputeGasLimit(tx) - feeRelayedTx := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) - - tx.GasUsed = gasUsed + gasUsedRelayedTx - - fee.Add(fee, feeRelayedTx) - tx.Fee = fee.String() - } else { - gasUsed, fee := gfp.feeComputer.ComputeGasUsedAndFeeBasedOnRefundValue(tx, big.NewInt(0)) - tx.GasUsed = gasUsed - tx.Fee = fee.String() - } + gfp.setGasUsedAndFeeBaseOnRefundValue(tx, userTx, big.NewInt(0)) } if core.SignalErrorOperation == event.Identifier { fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, tx.GasLimit) diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index f66ffd3f9cf..30bcf0fca76 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -163,24 +163,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResults( } if isSCRForSenderWithRefund(scr, txHashHex, txWithResults.GetTxHandler()) || isRefundForRelayed(scr, txWithResults.GetTxHandler()) { - if !check.IfNil(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, scr.Value) - - tx := txWithResults.GetTxHandler() - gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) - feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) - - txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) - txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) - hasRefund = true - - break - } - - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), scr.Value) - - txWithResults.GetFeeInfo().SetGasUsed(gasUsed) - txWithResults.GetFeeInfo().SetFee(fee) + tep.setGasUsedAndFeeBasedOnRefundValue(txWithResults, userTx, scr.Value, epoch) hasRefund = true break } @@ -271,22 +254,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( for _, event := range txWithResults.log.GetLogEvents() { if core.WriteLogIdentifier == string(event.GetIdentifier()) && !hasRefund { - if !check.IfNil(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, big.NewInt(0)) - - gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) - feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) - - txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) - txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) - - break - } - - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), big.NewInt(0)) - txWithResults.GetFeeInfo().SetGasUsed(gasUsed) - txWithResults.GetFeeInfo().SetFee(fee) - + tep.setGasUsedAndFeeBasedOnRefundValue(txWithResults, userTx, big.NewInt(0), epoch) continue } if core.SignalErrorOperation == string(event.GetIdentifier()) { @@ -295,7 +263,30 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( txWithResults.GetFeeInfo().SetFee(fee) } } +} + +func (tep *transactionsFeeProcessor) setGasUsedAndFeeBasedOnRefundValue( + txWithResults *transactionWithResults, + userTx data.TransactionHandler, + refund *big.Int, + epoch uint32, +) { + if !check.IfNil(userTx) && tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) { + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(userTx, refund) + + tx := txWithResults.GetTxHandler() + gasUsedRelayedTx := tep.txFeeCalculator.ComputeGasLimit(tx) + feeRelayedTx := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(tx, gasUsedRelayedTx) + + txWithResults.GetFeeInfo().SetGasUsed(gasUsed + gasUsedRelayedTx) + txWithResults.GetFeeInfo().SetFee(fee.Add(fee, feeRelayedTx)) + + return + } + gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), refund) + txWithResults.GetFeeInfo().SetGasUsed(gasUsed) + txWithResults.GetFeeInfo().SetFee(fee) } func (tep *transactionsFeeProcessor) prepareScrsNoTx(transactionsAndScrs *transactionsAndScrsHolder) error {