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 new file mode 100644 index 00000000000..f766ccddbf5 --- /dev/null +++ b/.github/workflows/build_and_run_chain_simulator_and_execute_system_test.yml @@ -0,0 +1,316 @@ +name: Chain Simulator Build and Integration Test + +on: + pull_request: + branches: + - 'main' + - 'master' + - 'rc/*' + workflow_dispatch: + issue_comment: + types: [created] + +permissions: + issues: write + pull-requests: write + contents: read + +jobs: + build-and-test: + if: | + github.event_name == 'pull_request' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, 'Run Tests:')) || + github.event_name == 'workflow_dispatch' + + strategy: + matrix: + #TODO Include Macos support later on + runs-on: [ubuntu-latest] + runs-on: ${{ matrix.runs-on }} + env: + BRANCH_NAME: ${{ github.head_ref || github.ref_name }} + TARGET_BRANCH: "" + MX_CHAIN_GO_TARGET_BRANCH: "" + MX_CHAIN_SIMULATOR_TARGET_BRANCH: "" + MX_CHAIN_TESTING_SUITE_TARGET_BRANCH: "" + + steps: + - name: Determine Target Branches + id: target_branch + run: | + echo "CURRENT_BRANCH=${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}}" >> $GITHUB_ENV + + # Default target branches based on the PR base branch + if [[ "${{ github.event.pull_request.base.ref }}" == "main" ]]; then + echo "MX_CHAIN_SIMULATOR_TARGET_BRANCH=main" >> $GITHUB_ENV + echo "MX_CHAIN_TESTING_SUITE_TARGET_BRANCH=main" >> $GITHUB_ENV + elif [[ "${{ github.event.pull_request.base.ref }}" == "master" ]]; then + echo "MX_CHAIN_SIMULATOR_TARGET_BRANCH=main" >> $GITHUB_ENV + echo "MX_CHAIN_TESTING_SUITE_TARGET_BRANCH=main" >> $GITHUB_ENV + else + echo "MX_CHAIN_SIMULATOR_TARGET_BRANCH=${{ github.event.pull_request.base.ref }}" >> $GITHUB_ENV + echo "MX_CHAIN_TESTING_SUITE_TARGET_BRANCH=${{ github.event.pull_request.base.ref }}" >> $GITHUB_ENV + fi + + # Always set MX_CHAIN_GO_TARGET_BRANCH based on the PR base branch + echo "MX_CHAIN_GO_TARGET_BRANCH=${{ github.event.pull_request.base.ref }}" >> $GITHUB_ENV + + + - name: Fetch and Parse Last Comment for Branches + uses: actions/github-script@v7 + id: fetch_and_parse_last_comment + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + // Get the latest comment + const comments = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + }); + + const lastComment = comments.data.pop(); // Get the last comment + + if (lastComment && lastComment.body.includes('Run Tests:')) { + const body = lastComment.body.trim(); + core.setOutput('latest_comment', body); + + // Parse the branches from the last comment + const simulatorBranchMatch = body.match(/mx-chain-simulator-go:\s*(\S+)/); + const testingSuiteBranchMatch = body.match(/mx-chain-testing-suite:\s*(\S+)/); + + // Override the target branches if specified + if (simulatorBranchMatch) { + core.exportVariable('MX_CHAIN_SIMULATOR_TARGET_BRANCH', simulatorBranchMatch[1]); + } + if (testingSuiteBranchMatch) { + core.exportVariable('MX_CHAIN_TESTING_SUITE_TARGET_BRANCH', testingSuiteBranchMatch[1]); + } + } else { + core.info('The last comment does not contain "Run Tests:". Skipping branch override.'); + } + + + - name: Print Target Branches + run: | + echo "Current branch mx-chain-go: ${{ env.CURRENT_BRANCH }}" + echo "mx-chain-go target branch: ${{ env.MX_CHAIN_GO_TARGET_BRANCH }}" + echo "mx-chain-simulator-go target branch: ${{ env.MX_CHAIN_SIMULATOR_TARGET_BRANCH }}" + echo "mx-chain-testing-suite target branch: ${{ env.MX_CHAIN_TESTING_SUITE_TARGET_BRANCH }}" + + - name: Set up Go 1.20.7 + uses: actions/setup-go@v3 + with: + go-version: 1.20.7 + id: go + + - name: Checkout mx-chain-go + uses: actions/checkout@v4 + with: + repository: 'multiversx/mx-chain-go' + ref: ${{ github.head_ref }} + fetch-depth: 0 + path: 'mx-chain-go' + + - name: Get Latest mx-chain-go Commit Hash + run: | + cd mx-chain-go + current_branch=$(git symbolic-ref --short HEAD) + echo "CURRENT_BRANCH=${current_branch}" >> $GITHUB_ENV + git fetch origin ${current_branch} --prune + latest_commit_hash=$(git rev-parse origin/${current_branch}) + echo "LATEST_COMMIT_HASH=${latest_commit_hash}" >> $GITHUB_ENV + echo "Latest commit hash: ${latest_commit_hash}" + + - name: Checkout mx-chain-simulator-go + uses: actions/checkout@v4 + with: + repository: 'multiversx/mx-chain-simulator-go' + ref: ${{ env.MX_CHAIN_SIMULATOR_TARGET_BRANCH || github.event.pull_request.base.ref }} + path: 'mx-chain-simulator-go' + + - name: Set up Python 3.10 + uses: actions/setup-python@v2 + with: + python-version: '3.10' + + - name: Install Python Dependencies and Update go.mod + run: | + cd mx-chain-simulator-go + pip install -r scripts/update-go-mod/requirements.txt + python scripts/update-go-mod/update-go-mod.py $LATEST_COMMIT_HASH + + - name: Run go build + run: | + cd mx-chain-simulator-go/cmd/chainsimulator + go build + echo "CHAIN_SIMULATOR_BUILD_PATH=$(pwd)" >> $GITHUB_ENV + + - name: Checkout mx-chain-testing-suite + uses: actions/checkout@v4 + with: + repository: 'multiversx/mx-chain-testing-suite' + path: 'mx-chain-testing-suite' + fetch-depth: 0 + ref: ${{ env.MX_CHAIN_TESTING_SUITE_TARGET_BRANCH || github.event.pull_request.base.ref }} + token: ${{ secrets.MVX_TESTER_GH_TOKEN }} + + - name: Install Dependencies + run: | + pip install -r mx-chain-testing-suite/requirements.txt + echo "PYTHONPATH=mx-chain-testing-suite" >> $GITHUB_ENV + + + - 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_EXIT_CODE=$? + set -e + echo "PYTEST_EXIT_CODE=$PYTEST_EXIT_CODE" >> $GITHUB_ENV + echo "Pytest exit code: $PYTEST_EXIT_CODE" + if [ -f "report.html" ]; then + echo "Report generated successfully." + mkdir -p ./reports + mv report.html ./reports/ + else + echo "Report not found." + fi + + - name: Upload test report + if: always() + uses: actions/upload-artifact@v3 + with: + name: pytest-report-${{ github.run_id }} + path: reports/report.html + + - name: Deploy Report to GitHub Pages + if: always() + id: deploy_report + run: | + # Navigate to the mx-chain-testing-suite directory + cd mx-chain-testing-suite + + # Configure Git user + git config user.name "GitHub Action" + git config user.email "action@github.com" + + # Check if the report exists + if [ -f "../reports/report.html" ]; then + # Ensure we're on the 'gh-pages' branch and up to date + git fetch --all + git checkout gh-pages || git checkout --orphan gh-pages + + # Create a new directory for the report based on the current timestamp + TIMESTAMP=$(date +'%d%m%Y-%H%M%S') + echo "TIMESTAMP=$TIMESTAMP" >> $GITHUB_ENV + REPORT_DIR="reports/${BRANCH_NAME}/${TIMESTAMP}" + mkdir -p $REPORT_DIR + + # Move the report into the new directory + cp ../reports/report.html $REPORT_DIR/index.html + + # Add and commit only the new report + git add $REPORT_DIR/index.html + git commit -m "Deploy Test Report at $BRANCH_NAME/$TIMESTAMP" + + # Set remote URL with authentication token + git remote set-url origin https://x-access-token:${{ secrets.MVX_TESTER_GH_TOKEN }}@github.com/multiversx/mx-chain-testing-suite.git + + # Push changes to the remote 'gh-pages' branch + git push --force origin gh-pages + else + echo "Report file not found, skipping deployment." + fi + + + - name: Update Index Page + if: always() + run: | + cd mx-chain-testing-suite + git fetch --all + git checkout gh-pages || git checkout --orphan gh-pages + if [ -d "docs" ]; then + cd docs + echo "

Test Reports

" >> index.html + git add index.html + git commit -m "Update Index of Reports" + git push origin gh-pages --force + else + mkdir -p docs + cd docs + echo "

Test Reports

" >> index.html + echo "Docs directory was not found and has been created." + fi + + - name: Comment PR with report link or error message + if: always() + uses: actions/github-script@v7 + env: + TIMESTAMP: ${{ env.TIMESTAMP }} + BRANCH_NAME: ${{ env.BRANCH_NAME }} + CURRENT_BRANCH: ${{ env.CURRENT_BRANCH }} + MX_CHAIN_GO_TARGET_BRANCH: ${{ env.MX_CHAIN_GO_TARGET_BRANCH }} + MX_CHAIN_SIMULATOR_TARGET_BRANCH: ${{ env.MX_CHAIN_SIMULATOR_TARGET_BRANCH }} + MX_CHAIN_TESTING_SUITE_TARGET_BRANCH: ${{ env.MX_CHAIN_TESTING_SUITE_TARGET_BRANCH }} + LATEST_COMMIT_HASH: ${{ env.LATEST_COMMIT_HASH }} + PYTEST_EXIT_CODE: ${{ env.PYTEST_EXIT_CODE }} + + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const timestamp = process.env.TIMESTAMP; + const branchName = process.env.BRANCH_NAME; + const currentBranch = process.env.CURRENT_BRANCH; + const goTargetBranch = process.env.MX_CHAIN_GO_TARGET_BRANCH; + const simulatorTargetBranch = process.env.MX_CHAIN_SIMULATOR_TARGET_BRANCH; + const testingSuiteTargetBranch = process.env.MX_CHAIN_TESTING_SUITE_TARGET_BRANCH; + const commitHash = process.env.LATEST_COMMIT_HASH; + const exitCode = process.env.PYTEST_EXIT_CODE; + const issue_number = context.issue.number; + const owner = context.repo.owner; + const repo = context.repo.repo; + let message; + + if (timestamp && branchName && timestamp !== "" && branchName !== "") { + const reportUrl = `https://multiversx.github.io/mx-chain-testing-suite/reports/${branchName}/${timestamp}/index.html`; + message = ` + 📊 **MultiversX Automated Test Report:** [View Report](${reportUrl}) + + 🔄 **Build Details:** + - **mx-chain-go Commit Hash:** \`${commitHash}\` + - **Current Branch:** \`${currentBranch}\` + - **mx-chain-go Target Branch:** \`${goTargetBranch}\` + - **mx-chain-simulator-go Target Branch:** \`${simulatorTargetBranch}\` + - **mx-chain-testing-suite Target Branch:** \`${testingSuiteTargetBranch}\` + + 🚀 **Environment Variables:** + - **TIMESTAMP:** \`${timestamp}\` + - **PYTEST_EXIT_CODE:** \`${exitCode}\` + 🎉 **MultiversX CI/CD Workflow Complete!** + `; + } else { + message = "⚠️ No report was generated due to an error or cancellation of the process.\nPlease checkout gh action logs for details"; + } + + github.rest.issues.createComment({ + issue_number: issue_number, + owner: owner, + repo: repo, + body: message + }); + + - name: Fail job if tests failed + if: always() + run: | + if [ "${{ env.PYTEST_EXIT_CODE }}" != "0" ]; then + echo "Tests failed with exit code ${{ env.PYTEST_EXIT_CODE }}" + exit 1 + else + echo "Tests passed successfully." + fi \ No newline at end of file diff --git a/api/errors/errors.go b/api/errors/errors.go index 30cfb923bbd..3f4e495b9d2 100644 --- a/api/errors/errors.go +++ b/api/errors/errors.go @@ -64,6 +64,9 @@ var ErrTxGenerationFailed = errors.New("transaction generation failed") // ErrValidationEmptyTxHash signals that an empty tx hash was provided var ErrValidationEmptyTxHash = errors.New("TxHash is empty") +// ErrValidationEmptySCRHash signals that provided smart contract result hash is empty +var ErrValidationEmptySCRHash = errors.New("SCRHash is empty") + // ErrInvalidBlockNonce signals that an invalid block nonce was provided var ErrInvalidBlockNonce = errors.New("invalid block nonce") @@ -79,6 +82,9 @@ var ErrValidationEmptyBlockHash = errors.New("block hash is empty") // ErrGetTransaction signals an error happening when trying to fetch a transaction var ErrGetTransaction = errors.New("getting transaction failed") +// ErrGetSmartContractResults signals an error happening when trying to fetch smart contract results +var ErrGetSmartContractResults = errors.New("getting smart contract results failed") + // ErrGetBlock signals an error happening when trying to fetch a block var ErrGetBlock = errors.New("getting block failed") diff --git a/api/groups/transactionGroup.go b/api/groups/transactionGroup.go index 29d07de2640..f35969ed701 100644 --- a/api/groups/transactionGroup.go +++ b/api/groups/transactionGroup.go @@ -26,11 +26,13 @@ const ( simulateTransactionEndpoint = "/transaction/simulate" sendMultipleTransactionsEndpoint = "/transaction/send-multiple" getTransactionEndpoint = "/transaction/:hash" + getScrsByTxHashEndpoint = "/transaction/scrs-by-tx-hash/:txhash" sendTransactionPath = "/send" simulateTransactionPath = "/simulate" costPath = "/cost" sendMultiplePath = "/send-multiple" getTransactionPath = "/:txhash" + getScrsByTxHashPath = "/scrs-by-tx-hash/:txhash" getTransactionsPool = "/pool" queryParamWithResults = "withResults" @@ -39,6 +41,7 @@ const ( queryParamFields = "fields" queryParamLastNonce = "last-nonce" queryParamNonceGaps = "nonce-gaps" + queryParameterScrHash = "scrHash" ) // transactionFacadeHandler defines the methods to be implemented by a facade for transaction requests @@ -49,6 +52,7 @@ type transactionFacadeHandler interface { SendBulkTransactions([]*transaction.Transaction) (uint64, error) SimulateTransactionExecution(tx *transaction.Transaction) (*txSimData.SimulationResultsWithVMOutput, error) GetTransaction(hash string, withResults bool) (*transaction.ApiTransactionResult, error) + GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) GetTransactionsPool(fields string) (*common.TransactionsPoolAPIResponse, error) GetTransactionsPoolForSender(sender, fields string) (*common.TransactionsPoolForSenderApiResponse, error) GetLastPoolNonceForSender(sender string) (uint64, error) @@ -137,6 +141,17 @@ func NewTransactionGroup(facade transactionFacadeHandler) (*transactionGroup, er }, }, }, + { + Path: getScrsByTxHashPath, + Method: http.MethodGet, + Handler: tg.getScrsByTxHash, + AdditionalMiddlewares: []shared.AdditionalMiddleware{ + { + Middleware: middleware.CreateEndpointThrottlerFromFacade(getScrsByTxHashEndpoint, facade), + Position: shared.Before, + }, + }, + }, } tg.endpoints = endpoints @@ -182,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, @@ -268,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, @@ -363,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 } @@ -421,6 +388,57 @@ func (tg *transactionGroup) sendMultipleTransactions(c *gin.Context) { ) } +func (tg *transactionGroup) getScrsByTxHash(c *gin.Context) { + txhash := c.Param("txhash") + if txhash == "" { + c.JSON( + http.StatusBadRequest, + shared.GenericAPIResponse{ + Data: nil, + Error: fmt.Sprintf("%s: %s", errors.ErrValidation.Error(), errors.ErrValidationEmptyTxHash.Error()), + Code: shared.ReturnCodeRequestError, + }, + ) + return + } + scrHashStr := c.Request.URL.Query().Get(queryParameterScrHash) + if scrHashStr == "" { + c.JSON( + http.StatusBadRequest, + shared.GenericAPIResponse{ + Data: nil, + Error: fmt.Sprintf("%s: %s", errors.ErrValidation.Error(), errors.ErrValidationEmptySCRHash.Error()), + Code: shared.ReturnCodeRequestError, + }, + ) + return + } + + start := time.Now() + scrs, err := tg.getFacade().GetSCRsByTxHash(txhash, scrHashStr) + if err != nil { + c.JSON( + http.StatusInternalServerError, + shared.GenericAPIResponse{ + Data: nil, + Error: fmt.Sprintf("%s: %s", errors.ErrGetSmartContractResults.Error(), err.Error()), + Code: shared.ReturnCodeInternalError, + }, + ) + return + } + logging.LogAPIActionDurationIfNeeded(start, "API call: GetSCRsByTxHash") + + c.JSON( + http.StatusOK, + shared.GenericAPIResponse{ + Data: gin.H{"scrs": scrs}, + Error: "", + Code: shared.ReturnCodeSuccess, + }, + ) +} + // getTransaction returns transaction details for a given txhash func (tg *transactionGroup) getTransaction(c *gin.Context) { txhash := c.Param("txhash") @@ -490,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, @@ -716,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) @@ -840,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 f183dd30b4c..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() @@ -343,6 +342,76 @@ func TestTransactionGroup_sendTransaction(t *testing.T) { }) } +func TestTransactionsGroup_getSCRsByTxHash(t *testing.T) { + t.Parallel() + + t.Run("get SCRsByTxHash empty scr hash should error", func(t *testing.T) { + facade := &mock.FacadeStub{} + + transactionGroup, err := groups.NewTransactionGroup(facade) + require.NoError(t, err) + + ws := startWebServer(transactionGroup, "transaction", getTransactionRoutesConfig()) + + req, _ := http.NewRequest(http.MethodGet, "/transaction/scrs-by-tx-hash/txHash", bytes.NewBuffer([]byte{})) + 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.ErrValidationEmptySCRHash.Error())) + assert.Empty(t, txResp.Data) + }) + t.Run("get scrs facade error", func(t *testing.T) { + localErr := fmt.Errorf("error") + facade := &mock.FacadeStub{ + GetSCRsByTxHashCalled: func(txHash string, scrHash string) ([]*dataTx.ApiSmartContractResult, error) { + return nil, localErr + }, + } + + transactionGroup, err := groups.NewTransactionGroup(facade) + require.NoError(t, err) + + ws := startWebServer(transactionGroup, "transaction", getTransactionRoutesConfig()) + + req, _ := http.NewRequest(http.MethodGet, "/transaction/scrs-by-tx-hash/txhash?scrHash=hash", bytes.NewBuffer([]byte{})) + resp := httptest.NewRecorder() + ws.ServeHTTP(resp, req) + + txResp := shared.GenericAPIResponse{} + loadResponse(resp.Body, &txResp) + + assert.Equal(t, http.StatusInternalServerError, resp.Code) + assert.True(t, strings.Contains(txResp.Error, localErr.Error())) + assert.Empty(t, txResp.Data) + }) + t.Run("get scrs should work", func(t *testing.T) { + facade := &mock.FacadeStub{ + GetSCRsByTxHashCalled: func(txHash string, scrHash string) ([]*dataTx.ApiSmartContractResult, error) { + return []*dataTx.ApiSmartContractResult{}, nil + }, + } + + transactionGroup, err := groups.NewTransactionGroup(facade) + require.NoError(t, err) + + ws := startWebServer(transactionGroup, "transaction", getTransactionRoutesConfig()) + + req, _ := http.NewRequest(http.MethodGet, "/transaction/scrs-by-tx-hash/txhash?scrHash=hash", bytes.NewBuffer([]byte{})) + resp := httptest.NewRecorder() + ws.ServeHTTP(resp, req) + + txResp := shared.GenericAPIResponse{} + loadResponse(resp.Body, &txResp) + + assert.Equal(t, http.StatusOK, resp.Code) + assert.Equal(t, "", txResp.Error) + }) +} + func TestTransactionGroup_sendMultipleTransactions(t *testing.T) { t.Parallel() @@ -521,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() @@ -642,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() @@ -1125,67 +1192,9 @@ func getTransactionRoutesConfig() config.ApiRoutesConfig { {Name: "/:txhash", Open: true}, {Name: "/:txhash/status", Open: true}, {Name: "/simulate", Open: true}, + {Name: "/scrs-by-tx-hash/:txhash", Open: true}, }, }, }, } } - -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/api/mock/facadeStub.go b/api/mock/facadeStub.go index e40645c1ac3..62de2febc81 100644 --- a/api/mock/facadeStub.go +++ b/api/mock/facadeStub.go @@ -97,6 +97,16 @@ type FacadeStub struct { GetWaitingEpochsLeftForPublicKeyCalled func(publicKey string) (uint32, error) P2PPrometheusMetricsEnabledCalled func() bool AuctionListHandler func() ([]*common.AuctionListValidatorAPIResponse, error) + GetSCRsByTxHashCalled func(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) +} + +// GetSCRsByTxHash - +func (f *FacadeStub) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + if f.GetSCRsByTxHashCalled != nil { + return f.GetSCRsByTxHashCalled(txHash, scrHash) + } + + return nil, nil } // GetTokenSupply - diff --git a/api/shared/interface.go b/api/shared/interface.go index 4b775ebdd39..206cea6ee30 100644 --- a/api/shared/interface.go +++ b/api/shared/interface.go @@ -135,6 +135,7 @@ type FacadeHandler interface { GetEligibleManagedKeys() ([]string, error) GetWaitingManagedKeys() ([]string, error) GetWaitingEpochsLeftForPublicKey(publicKey string) (uint32, error) + GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) P2PPrometheusMetricsEnabled() bool IsInterfaceNil() bool } diff --git a/cmd/node/config/api.toml b/cmd/node/config/api.toml index a10ec049554..fcf9cf7fc0b 100644 --- a/cmd/node/config/api.toml +++ b/cmd/node/config/api.toml @@ -221,6 +221,9 @@ # /transaction/:txhash will return the transaction in JSON format based on its hash { Name = "/:txhash", Open = true }, + + # /transaction/scrs-by-tx-hash/:txhash will return the smart contract results generated by the provided transaction hash + { Name = "/scrs-by-tx-hash/:txhash", Open = true }, ] [APIPackages.block] 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/cmd/node/config/enableEpochs.toml b/cmd/node/config/enableEpochs.toml index f088f7b549c..9ca2083a352 100644 --- a/cmd/node/config/enableEpochs.toml +++ b/cmd/node/config/enableEpochs.toml @@ -309,6 +309,9 @@ # AlwaysMergeContextsInEEIEnableEpoch represents the epoch in which the EEI will always merge the contexts AlwaysMergeContextsInEEIEnableEpoch = 1 + # UseGasBoundedShouldFailExecutionEnableEpoch represents the epoch when use bounded gas function should fail execution in case of error + UseGasBoundedShouldFailExecutionEnableEpoch = 1 + # DynamicESDTEnableEpoch represents the epoch when dynamic NFT feature is enabled DynamicESDTEnableEpoch = 4 @@ -321,15 +324,15 @@ # 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 = 4 + # BLSMultiSignerEnableEpoch represents the activation epoch for different types of BLS multi-signers BLSMultiSignerEnableEpoch = [ { EnableEpoch = 0, Type = "no-KOSK" }, diff --git a/cmd/node/config/external.toml b/cmd/node/config/external.toml index 1058e0c3fb7..6fbbbb195c6 100644 --- a/cmd/node/config/external.toml +++ b/cmd/node/config/external.toml @@ -51,7 +51,7 @@ # URL for the WebSocket client/server connection # This value represents the IP address and port number that the WebSocket client or server will use to establish a connection. - URL = "127.0.0.1:22111" + URL = "ws://127.0.0.1:22111" # After a message will be sent it will wait for an ack message if this flag is enabled WithAcknowledge = true diff --git a/common/constants.go b/common/constants.go index 984dec87b07..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" @@ -737,6 +734,9 @@ const ( // MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch represents the epoch when enshrined sovereign opcodes are enabled MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch = "erd_multi_esdt_transfer_execute_by_user_enable_epoch" + // MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch represents the epoch when the fix for relayed move balance to non-payable sc is enabled + MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch = "erd_fix_relayed_move_balance_to_non_payable_sc_enable_epoch" + // MetricMaxNodesChangeEnableEpoch holds configuration for changing the maximum number of nodes and the enabling epoch MetricMaxNodesChangeEnableEpoch = "erd_max_nodes_change_enable_epoch" @@ -1226,12 +1226,13 @@ const ( CleanupAuctionOnLowWaitingListFlag core.EnableEpochFlag = "CleanupAuctionOnLowWaitingListFlag" StakingV4StartedFlag core.EnableEpochFlag = "StakingV4StartedFlag" AlwaysMergeContextsInEEIFlag core.EnableEpochFlag = "AlwaysMergeContextsInEEIFlag" + UseGasBoundedShouldFailExecutionFlag core.EnableEpochFlag = "UseGasBoundedShouldFailExecutionFlag" DynamicESDTFlag core.EnableEpochFlag = "DynamicEsdtFlag" 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" // all new flags must be added to createAllFlagsMap method, as part of enableEpochsHandler allFlagsDefined ) diff --git a/common/enablers/enableEpochsHandler.go b/common/enablers/enableEpochsHandler.go index d3df21b6bbb..65cc7762796 100644 --- a/common/enablers/enableEpochsHandler.go +++ b/common/enablers/enableEpochsHandler.go @@ -732,6 +732,12 @@ func (handler *enableEpochsHandler) createAllFlagsMap() { }, activationEpoch: handler.enableEpochsConfig.AlwaysMergeContextsInEEIEnableEpoch, }, + common.UseGasBoundedShouldFailExecutionFlag: { + isActiveInEpoch: func(epoch uint32) bool { + return epoch >= handler.enableEpochsConfig.UseGasBoundedShouldFailExecutionEnableEpoch + }, + activationEpoch: handler.enableEpochsConfig.UseGasBoundedShouldFailExecutionEnableEpoch, + }, common.DynamicESDTFlag: { isActiveInEpoch: func(epoch uint32) bool { return epoch >= handler.enableEpochsConfig.DynamicESDTEnableEpoch @@ -756,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 @@ -774,6 +774,12 @@ func (handler *enableEpochsHandler) createAllFlagsMap() { }, activationEpoch: handler.enableEpochsConfig.MultiESDTNFTTransferAndExecuteByUserEnableEpoch, }, + common.FixRelayedMoveBalanceToNonPayableSCFlag: { + isActiveInEpoch: func(epoch uint32) bool { + return epoch >= handler.enableEpochsConfig.FixRelayedMoveBalanceToNonPayableSCEnableEpoch + }, + activationEpoch: handler.enableEpochsConfig.FixRelayedMoveBalanceToNonPayableSCEnableEpoch, + }, } } diff --git a/common/enablers/enableEpochsHandler_test.go b/common/enablers/enableEpochsHandler_test.go index 72fafc5a689..d0f9191055e 100644 --- a/common/enablers/enableEpochsHandler_test.go +++ b/common/enablers/enableEpochsHandler_test.go @@ -119,9 +119,10 @@ func createEnableEpochsConfig() config.EnableEpochs { DynamicESDTEnableEpoch: 102, EGLDInMultiTransferEnableEpoch: 103, CryptoOpcodesV2EnableEpoch: 104, - RelayedTransactionsV3EnableEpoch: 105, - FixRelayedBaseCostEnableEpoch: 106, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 107, + FixRelayedBaseCostEnableEpoch: 105, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 106, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 107, + UseGasBoundedShouldFailExecutionEnableEpoch: 108, } } @@ -322,8 +323,8 @@ 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)) } func TestEnableEpochsHandler_GetActivationEpoch(t *testing.T) { @@ -440,12 +441,13 @@ func TestEnableEpochsHandler_GetActivationEpoch(t *testing.T) { require.Equal(t, cfg.CleanupAuctionOnLowWaitingListEnableEpoch, handler.GetActivationEpoch(common.CleanupAuctionOnLowWaitingListFlag)) require.Equal(t, cfg.StakingV4Step1EnableEpoch, handler.GetActivationEpoch(common.StakingV4StartedFlag)) require.Equal(t, cfg.AlwaysMergeContextsInEEIEnableEpoch, handler.GetActivationEpoch(common.AlwaysMergeContextsInEEIFlag)) + require.Equal(t, cfg.UseGasBoundedShouldFailExecutionEnableEpoch, handler.GetActivationEpoch(common.UseGasBoundedShouldFailExecutionFlag)) 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)) } func TestEnableEpochsHandler_IsInterfaceNil(t *testing.T) { 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/config/epochConfig.go b/config/epochConfig.go index 7f965e3c5c5..a7fd67c680a 100644 --- a/config/epochConfig.go +++ b/config/epochConfig.go @@ -114,13 +114,14 @@ type EnableEpochs struct { StakingV4Step3EnableEpoch uint32 CleanupAuctionOnLowWaitingListEnableEpoch uint32 AlwaysMergeContextsInEEIEnableEpoch uint32 + UseGasBoundedShouldFailExecutionEnableEpoch uint32 DynamicESDTEnableEpoch uint32 EGLDInMultiTransferEnableEpoch uint32 CryptoOpcodesV2EnableEpoch uint32 UnJailCleanupEnableEpoch uint32 - RelayedTransactionsV3EnableEpoch uint32 FixRelayedBaseCostEnableEpoch uint32 MultiESDTNFTTransferAndExecuteByUserEnableEpoch uint32 + FixRelayedMoveBalanceToNonPayableSCEnableEpoch uint32 BLSMultiSignerEnableEpoch []MultiSignerConfig } diff --git a/config/tomlConfig_test.go b/config/tomlConfig_test.go index c6cecedc774..39a582b1ef2 100644 --- a/config/tomlConfig_test.go +++ b/config/tomlConfig_test.go @@ -863,17 +863,17 @@ func TestEnableEpochConfig(t *testing.T) { # CleanupAuctionOnLowWaitingListEnableEpoch represents the epoch when the cleanup auction on low waiting list is enabled CleanupAuctionOnLowWaitingListEnableEpoch = 95 + # UseGasBoundedShouldFailExecutionEnableEpoch represents the epoch when use bounded gas function should fail execution in case of error + 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 - - # RelayedTransactionsV3EnableEpoch represents the epoch when the relayed transactions V3 will be enabled - RelayedTransactionsV3EnableEpoch = 99 + CryptoOpcodesV2EnableEpoch = 99 # FixRelayedBaseCostEnableEpoch represents the epoch when the fix for relayed base cost will be enabled FixRelayedBaseCostEnableEpoch = 100 @@ -881,6 +881,9 @@ func TestEnableEpochConfig(t *testing.T) { # MultiESDTNFTTransferAndExecuteByUserEnableEpoch represents the epoch when enshrined sovereign cross chain opcodes are enabled MultiESDTNFTTransferAndExecuteByUserEnableEpoch = 101 + # FixRelayedMoveBalanceToNonPayableSCEnableEpoch represents the epoch when the fix for relayed move balance to non payable sc will be enabled + FixRelayedMoveBalanceToNonPayableSCEnableEpoch = 102 + # MaxNodesChangeEnableEpoch holds configuration for changing the maximum number of nodes and the enabling epoch MaxNodesChangeEnableEpoch = [ { EpochEnable = 44, MaxNumNodes = 2169, NodesToShufflePerShard = 80 }, @@ -994,12 +997,13 @@ func TestEnableEpochConfig(t *testing.T) { CurrentRandomnessOnSortingEnableEpoch: 93, AlwaysMergeContextsInEEIEnableEpoch: 94, CleanupAuctionOnLowWaitingListEnableEpoch: 95, - DynamicESDTEnableEpoch: 96, - EGLDInMultiTransferEnableEpoch: 97, - CryptoOpcodesV2EnableEpoch: 98, - RelayedTransactionsV3EnableEpoch: 99, + UseGasBoundedShouldFailExecutionEnableEpoch: 96, + DynamicESDTEnableEpoch: 97, + EGLDInMultiTransferEnableEpoch: 98, + CryptoOpcodesV2EnableEpoch: 99, FixRelayedBaseCostEnableEpoch: 100, MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 101, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 102, MaxNodesChangeEnableEpoch: []MaxNodesChangeConfig{ { EpochEnable: 44, diff --git a/docker/keygenerator/Dockerfile b/docker/keygenerator/Dockerfile index a73d7951d42..574f9ea15e5 100644 --- a/docker/keygenerator/Dockerfile +++ b/docker/keygenerator/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.20.7 as builder +FROM golang:1.20.7 AS builder RUN apt-get update && apt-get install -y WORKDIR /go/mx-chain-go diff --git a/docker/node/Dockerfile b/docker/node/Dockerfile index 2a341a8409b..205733030c1 100644 --- a/docker/node/Dockerfile +++ b/docker/node/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.20.7 as builder +FROM golang:1.20.7 AS builder RUN apt-get update && apt-get upgrade -y WORKDIR /go/mx-chain-go diff --git a/docker/seednode/Dockerfile b/docker/seednode/Dockerfile index 74cc250c047..0a88e94e2c0 100644 --- a/docker/seednode/Dockerfile +++ b/docker/seednode/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.20.7 as builder +FROM golang:1.20.7 AS builder RUN apt-get update && apt-get install -y WORKDIR /go/mx-chain-go diff --git a/docker/termui/Dockerfile b/docker/termui/Dockerfile index e22986033eb..22b053b64d4 100644 --- a/docker/termui/Dockerfile +++ b/docker/termui/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.20.7 as builder +FROM golang:1.20.7 AS builder RUN apt-get update && apt-get install -y WORKDIR /go/mx-chain-go COPY . . 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/facade/initial/initialNodeFacade.go b/facade/initial/initialNodeFacade.go index 7411a2078e9..d6043dbcd62 100644 --- a/facade/initial/initialNodeFacade.go +++ b/facade/initial/initialNodeFacade.go @@ -421,6 +421,11 @@ func (inf *initialNodeFacade) IsDataTrieMigrated(_ string, _ api.AccountQueryOpt return false, errNodeStarting } +// GetSCRsByTxHash return a nil slice and error +func (inf *initialNodeFacade) GetSCRsByTxHash(_ string, _ string) ([]*transaction.ApiSmartContractResult, error) { + return nil, errNodeStarting +} + // GetManagedKeysCount returns 0 func (inf *initialNodeFacade) GetManagedKeysCount() int { return 0 diff --git a/facade/interface.go b/facade/interface.go index 35f185874ed..309f6c98d6f 100644 --- a/facade/interface.go +++ b/facade/interface.go @@ -127,6 +127,7 @@ type ApiResolver interface { GetDirectStakedList(ctx context.Context) ([]*api.DirectStakedValue, error) GetDelegatorsList(ctx context.Context) ([]*api.Delegator, error) GetTransaction(hash string, withResults bool) (*transaction.ApiTransactionResult, error) + GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) GetTransactionsPool(fields string) (*common.TransactionsPoolAPIResponse, error) GetTransactionsPoolForSender(sender, fields string) (*common.TransactionsPoolForSenderApiResponse, error) GetLastPoolNonceForSender(sender string) (uint64, error) diff --git a/facade/mock/apiResolverStub.go b/facade/mock/apiResolverStub.go index 33bae8518aa..8e38ab6707d 100644 --- a/facade/mock/apiResolverStub.go +++ b/facade/mock/apiResolverStub.go @@ -50,6 +50,16 @@ type ApiResolverStub struct { GetEligibleManagedKeysCalled func() ([]string, error) GetWaitingManagedKeysCalled func() ([]string, error) GetWaitingEpochsLeftForPublicKeyCalled func(publicKey string) (uint32, error) + GetSCRsByTxHashCalled func(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) +} + +// GetSCRsByTxHash - +func (ars *ApiResolverStub) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + if ars.GetSCRsByTxHashCalled != nil { + return ars.GetSCRsByTxHashCalled(txHash, scrHash) + } + + return nil, nil } // GetTransaction - diff --git a/facade/nodeFacade.go b/facade/nodeFacade.go index 8bc696b6adc..c3a7f290edf 100644 --- a/facade/nodeFacade.go +++ b/facade/nodeFacade.go @@ -304,6 +304,11 @@ func (nf *nodeFacade) GetTransaction(hash string, withResults bool) (*transactio return nf.apiResolver.GetTransaction(hash, withResults) } +// GetSCRsByTxHash will return a list of smart contract results based on a provided tx hash and smart contract result hash +func (nf *nodeFacade) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + return nf.apiResolver.GetSCRsByTxHash(txHash, scrHash) +} + // GetTransactionsPool will return a structure containing the transactions pool that is to be returned on API calls func (nf *nodeFacade) GetTransactionsPool(fields string) (*common.TransactionsPoolAPIResponse, error) { return nf.apiResolver.GetTransactionsPool(fields) diff --git a/factory/api/apiResolverFactory.go b/factory/api/apiResolverFactory.go index dfefa56ff94..399ee4b1533 100644 --- a/factory/api/apiResolverFactory.go +++ b/factory/api/apiResolverFactory.go @@ -244,6 +244,8 @@ func CreateApiResolver(args *ApiResolverArgs) (facade.ApiResolver, error) { TxTypeHandler: txTypeHandler, LogsFacade: logsFacade, DataFieldParser: dataFieldParser, + TxMarshaller: args.CoreComponents.TxMarshalizer(), + EnableEpochsHandler: args.CoreComponents.EnableEpochsHandler(), } apiTransactionProcessor, err := transactionAPI.NewAPITransactionProcessor(argsAPITransactionProc) if err != nil { 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 93f3e1e95a3..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() @@ -178,6 +174,11 @@ func (pcf *processComponentsFactory) newShardBlockProcessor( return nil, err } + err = builtInFuncFactory.SetBlockchainHook(vmFactory.BlockChainHookImpl()) + if err != nil { + return nil, err + } + argsFactory := shard.ArgsNewIntermediateProcessorsContainerFactory{ ShardCoordinator: pcf.bootstrapComponents.ShardCoordinator(), Marshalizer: pcf.coreData.InternalMarshalizer(), @@ -228,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, @@ -242,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) @@ -285,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 { @@ -565,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, @@ -579,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..0c919b0ba95 100644 --- a/factory/processing/txSimulatorProcessComponents_test.go +++ b/factory/processing/txSimulatorProcessComponents_test.go @@ -8,8 +8,8 @@ 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" + "github.com/stretchr/testify/require" ) func TestManagedProcessComponents_createAPITransactionEvaluator(t *testing.T) { @@ -27,7 +27,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,18 +37,20 @@ 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)) + require.NoError(t, vmContainerFactory.Close()) }) t.Run("should work for metachain", func(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)) + require.NoError(t, vmContainerFactory.Close()) }) } 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 4667bd06e7e..75a2eee7f19 100644 --- a/go.mod +++ b/go.mod @@ -14,15 +14,15 @@ require ( github.com/gorilla/websocket v1.5.0 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.21 + github.com/multiversx/mx-chain-communication-go v1.1.1-0.20241021133229-d0833256e3ec + 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.4 + 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 - github.com/multiversx/mx-chain-vm-common-go v1.5.13 - github.com/multiversx/mx-chain-vm-go v1.5.32-0.20240808073353-f1fbbf147537 + github.com/multiversx/mx-chain-vm-common-go v1.5.16 + github.com/multiversx/mx-chain-vm-go v1.5.37 github.com/multiversx/mx-chain-vm-v1_2-go v1.2.68 github.com/multiversx/mx-chain-vm-v1_3-go v1.3.69 github.com/multiversx/mx-chain-vm-v1_4-go v1.4.98 diff --git a/go.sum b/go.sum index 11a9bc62556..4de240abdf8 100644 --- a/go.sum +++ b/go.sum @@ -385,24 +385,24 @@ github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/n github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU= github.com/multiversx/concurrent-map v0.1.4 h1:hdnbM8VE4b0KYJaGY5yJS2aNIW9TFFsUYwbO0993uPI= 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.21 h1:+XVKznPTlUU5EFS1A8chtS8fStW60upRIyF4Pgml19I= -github.com/multiversx/mx-chain-core-go v1.2.21/go.mod h1:B5zU4MFyJezmEzCsAHE9YNULmGCm2zbPHvl9hazNxmE= +github.com/multiversx/mx-chain-communication-go v1.1.1-0.20241021133229-d0833256e3ec h1:KwpeVZXSHzic8DV9zaJZmaBgDNIIpSdbGz4Q+9fZyiI= +github.com/multiversx/mx-chain-communication-go v1.1.1-0.20241021133229-d0833256e3ec/go.mod h1:WK6bP4pGEHGDDna/AYRIMtl6G9OA0NByI1Lw8PmOnRM= +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.4 h1:SjJk9G9SN8baz0sFIU2jymYCfx3XiikGEB2wW0jwvfw= -github.com/multiversx/mx-chain-es-indexer-go v1.7.4/go.mod h1:oGcRK2E3Syv6vRTszWrrb/TqD8akq0yeoMr1wPPiTO4= +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= github.com/multiversx/mx-chain-scenario-go v1.4.4/go.mod h1:kI+TWR3oIEgUkbwkHCPo2CQ3VjIge+ezGTibiSGwMxo= github.com/multiversx/mx-chain-storage-go v1.0.16 h1:l2lJq+EAN3YwLbjJrnoKfFd1/1Xmo9DcAUECND2obLs= github.com/multiversx/mx-chain-storage-go v1.0.16/go.mod h1:uM/z7YyqTOD3wgyH8TfapyEl5sb+7x/Jaxne4cfG4HI= -github.com/multiversx/mx-chain-vm-common-go v1.5.13 h1:ymnIHJW4Z4mFa0hZzla4fozkF30vjH5O1q+Y7Ftc+pQ= -github.com/multiversx/mx-chain-vm-common-go v1.5.13/go.mod h1:OSvFbzdWThfRbLZbUsEr7bikBSaLrPJQ2iUm9jw9nXQ= -github.com/multiversx/mx-chain-vm-go v1.5.32-0.20240808073353-f1fbbf147537 h1:x1Fn0tlkicBNsRB/co/c9TTjyvCrzmE/rVXA8uUWhII= -github.com/multiversx/mx-chain-vm-go v1.5.32-0.20240808073353-f1fbbf147537/go.mod h1:iq6sCPweoHC9Fx56uf8buPrqlGVGJKUMRFxTunzjvys= +github.com/multiversx/mx-chain-vm-common-go v1.5.16 h1:g1SqYjxl7K66Y1O/q6tvDJ37fzpzlxCSfRzSm/woQQY= +github.com/multiversx/mx-chain-vm-common-go v1.5.16/go.mod h1:1rSkXreUZNXyPTTdhj47M+Fy62yjxbu3aAsXEtKN3UY= +github.com/multiversx/mx-chain-vm-go v1.5.37 h1:Iy3KCvM+DOq1f9UPA7uYK/rI3ZbBOXc2CVNO2/vm5zw= +github.com/multiversx/mx-chain-vm-go v1.5.37/go.mod h1:nzLrWeXvfxCIiwj5uNBZq3d7stkXyeY+Fktfr4tTaiY= github.com/multiversx/mx-chain-vm-v1_2-go v1.2.68 h1:L3GoAVFtLLzr9ya0rVv1YdTUzS3MyM7kQNBSAjCNO2g= github.com/multiversx/mx-chain-vm-v1_2-go v1.2.68/go.mod h1:ixxwib+1pXwSDHG5Wa34v0SRScF+BwFzH4wFWY31saI= github.com/multiversx/mx-chain-vm-v1_3-go v1.3.69 h1:G/PLsyfQV4bMLs2amGRvaLKZoW1DC7M+7ecVaLuaCNc= diff --git a/integrationTests/chainSimulator/relayedTx/relayedTx_test.go b/integrationTests/chainSimulator/relayedTx/relayedTx_test.go index 72bc9575763..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,7 @@ 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" maxNumOfBlocksToGenerateWhenExecutingTx = 10 @@ -37,236 +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 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) - scCode := wasm.GetSCCode("testData/adder.wasm") - params := []string{scCode, wasm.VMTypeHex, wasm.DummyCodeMetadataHex, "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) - 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 TestFixRelayedMoveBalanceWithChainSimulator(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") @@ -295,8 +63,6 @@ func testFixRelayedMoveBalanceWithChainSimulatorScCall( cs := startChainSimulator(t, alterConfigsFunc) defer cs.Close() - pkConv := cs.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter() - initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(10)) relayer, err := cs.GenerateAndMintWalletAddress(0, initialBalance) require.NoError(t, err) @@ -309,16 +75,8 @@ func testFixRelayedMoveBalanceWithChainSimulatorScCall( err = cs.GenerateBlocks(1) require.NoError(t, err) - scCode := wasm.GetSCCode("testData/adder.wasm") - params := []string{scCode, wasm.VMTypeHex, wasm.DummyCodeMetadataHex, "00"} - txDataDeploy := strings.Join(params, "@") - deployTx := generateTransaction(owner.Bytes, 0, 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) + ownerNonce := uint64(0) + scAddressBytes := deployAdder(t, cs, owner, ownerNonce) // fast-forward until epoch 4 err = cs.GenerateBlocksUntilEpochIsReached(int32(4)) @@ -456,12 +214,15 @@ func testFixRelayedMoveBalanceWithChainSimulatorMoveBalance( } } -func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorInnerNotExecutable(t *testing.T) { +func TestRelayedTransactionFeeField(t *testing.T) { if testing.Short() { t.Skip("this is not a short test") } - cs := startChainSimulator(t, alterConfigsFuncRelayedV3EarlyActivation) + cs := startChainSimulator(t, func(cfg *config.Configs) { + cfg.EpochConfig.EnableEpochs.RelayedTransactionsEnableEpoch = 1 + cfg.EpochConfig.EnableEpochs.FixRelayedBaseCostEnableEpoch = 1 + }) defer cs.Close() initialBalance := big.NewInt(0).Mul(oneEGLD, big.NewInt(10)) @@ -471,114 +232,29 @@ func TestRelayedTransactionInMultiShardEnvironmentWithChainSimulatorInnerNotExec 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) + receiver, err := cs.GenerateAndMintWalletAddress(0, big.NewInt(0)) 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) + t.Run("relayed v1", func(t *testing.T) { + innerTx := generateTransaction(sender.Bytes, 0, receiver.Bytes, oneEGLD, "", minGasLimit) + buff, err := json.Marshal(innerTx) + require.NoError(t, err) - // generate few more blocks for the cross shard scrs to be done - err = cs.GenerateBlocks(maxNumOfBlocksToGenerateWhenExecutingTx) - require.NoError(t, err) + txData := []byte("relayedTx@" + hex.EncodeToString(buff)) + gasLimit := minGasLimit + len(txData)*gasPerDataByte + int(innerTx.GasLimit) + relayedTx := generateTransaction(relayer.Bytes, 0, sender.Bytes, big.NewInt(0), string(txData), uint64(gasLimit)) - expectedRelayerFee = core.SafeMul(uint64(expectedConsumedGasForGuardedInnerTx), minGasPrice) - checkBalance(t, cs, relayer, big.NewInt(0).Sub(relayerBalanceBeforeSuccessfullAttempt, expectedRelayerFee)) + result, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(relayedTx, maxNumOfBlocksToGenerateWhenExecutingTx) + require.NoError(t, err) - checkBalance(t, cs, receiver, oneEGLD) + 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) + }) } func startChainSimulator( @@ -630,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, @@ -696,12 +320,27 @@ func getBalance( return balance } -func checkBalance( +func deployAdder( t *testing.T, cs testsChainSimulator.ChainSimulator, - address dtos.WalletAddress, - expectedBalance *big.Int, -) { - balance := getBalance(t, cs, address) - require.Equal(t, expectedBalance.String(), balance.String()) + owner dtos.WalletAddress, + ownerNonce uint64, +) []byte { + pkConv := cs.GetNodeHandler(0).GetCoreComponents().AddressPubKeyConverter() + + err := cs.GenerateBlocks(1) + require.Nil(t, err) + + scCode := wasm.GetSCCode("testData/adder.wasm") + params := []string{scCode, wasm.VMTypeHex, wasm.DummyCodeMetadataHex, "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) + + return scAddressBytes } diff --git a/integrationTests/chainSimulator/vm/egldMultiTransfer_test.go b/integrationTests/chainSimulator/vm/egldMultiTransfer_test.go index 10a10cee5ad..5e9d641f90a 100644 --- a/integrationTests/chainSimulator/vm/egldMultiTransfer_test.go +++ b/integrationTests/chainSimulator/vm/egldMultiTransfer_test.go @@ -141,7 +141,7 @@ func TestChainSimulator_EGLD_MultiTransfer(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -275,7 +275,7 @@ func TestChainSimulator_EGLD_MultiTransfer_Insufficient_Funds(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -397,7 +397,7 @@ func TestChainSimulator_EGLD_MultiTransfer_Invalid_Value(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -519,7 +519,7 @@ func TestChainSimulator_Multiple_EGLD_Transfers(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -732,7 +732,7 @@ func TestChainSimulator_IssueToken_EGLDTicker(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) diff --git a/integrationTests/chainSimulator/vm/esdtImprovements_test.go b/integrationTests/chainSimulator/vm/esdtImprovements_test.go index 438660658f3..e0f23f1ce8c 100644 --- a/integrationTests/chainSimulator/vm/esdtImprovements_test.go +++ b/integrationTests/chainSimulator/vm/esdtImprovements_test.go @@ -219,7 +219,7 @@ func transferAndCheckTokensMetaData(t *testing.T, isCrossShard bool, isMultiTran } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -401,6 +401,18 @@ func checkMetaData( require.Equal(t, expectedMetaData.Attributes, []byte(hex.EncodeToString(retrievedMetaData.Attributes))) } +func checkReservedField( + t *testing.T, + cs testsChainSimulator.ChainSimulator, + addressBytes []byte, + tokenID []byte, + shardID uint32, + expectedReservedField []byte, +) { + esdtData := getESDTDataFromAcc(t, cs, addressBytes, tokenID, shardID) + require.Equal(t, expectedReservedField, esdtData.Reserved) +} + func checkMetaDataNotInAcc( t *testing.T, cs testsChainSimulator.ChainSimulator, @@ -599,19 +611,20 @@ func updateTokenIDTx(nonce uint64, sndAdr []byte, tokenID []byte) *transaction.T } } -func nftCreateTx( +func esdtNftCreateTx( nonce uint64, sndAdr []byte, tokenID []byte, metaData *txsFee.MetaData, + quantity int64, ) *transaction.Transaction { txDataField := bytes.Join( [][]byte{ []byte(core.BuiltInFunctionESDTNFTCreate), []byte(hex.EncodeToString(tokenID)), - []byte(hex.EncodeToString(big.NewInt(1).Bytes())), // quantity + []byte(hex.EncodeToString(big.NewInt(quantity).Bytes())), // quantity metaData.Name, - []byte(hex.EncodeToString(big.NewInt(10).Bytes())), + metaData.Royalties, metaData.Hash, metaData.Attributes, metaData.Uris[0], @@ -853,7 +866,7 @@ func TestChainSimulator_CreateTokensAfterActivation(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -992,7 +1005,7 @@ func TestChainSimulator_ESDTMetaDataRecreate(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -1194,7 +1207,7 @@ func TestChainSimulator_ESDTMetaDataUpdate(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -1236,35 +1249,7 @@ func TestChainSimulator_ESDTMetaDataUpdate(t *testing.T) { newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) newMetaData.Attributes = []byte(hex.EncodeToString([]byte("attributes2"))) - txDataField := bytes.Join( - [][]byte{ - []byte(core.ESDTMetaDataUpdate), - []byte(hex.EncodeToString(tokenIDs[i])), - newMetaData.Nonce, - newMetaData.Name, - []byte(hex.EncodeToString(big.NewInt(10).Bytes())), - newMetaData.Hash, - newMetaData.Attributes, - newMetaData.Uris[0], - newMetaData.Uris[1], - newMetaData.Uris[2], - }, - []byte("@"), - ) - - tx = &transaction.Transaction{ - Nonce: nonce, - SndAddr: addrs[0].Bytes, - RcvAddr: addrs[0].Bytes, - GasLimit: 10_000_000, - GasPrice: minGasPrice, - Signature: []byte("dummySig"), - Data: txDataField, - Value: big.NewInt(0), - ChainID: []byte(configs.ChainID), - Version: 1, - } - + tx = esdtMetaDataUpdateTx(tokenIDs[i], newMetaData, nonce, addrs[0].Bytes) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) require.NotNil(t, txResult) @@ -1422,7 +1407,7 @@ func TestChainSimulator_ESDTModifyCreator(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[1].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[1].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -1482,7 +1467,12 @@ func TestChainSimulator_ESDTModifyCreator(t *testing.T) { require.Equal(t, "success", txResult.Status.String()) - retrievedMetaData := getMetaDataFromAcc(t, cs, core.SystemAccountAddress, tokenIDs[i], shardID) + retrievedMetaData := &esdt.MetaData{} + if bytes.Equal(tokenIDs[i], nftTokenID) { + retrievedMetaData = getMetaDataFromAcc(t, cs, newCreatorAddress.Bytes, tokenIDs[i], shardID) + } else { + retrievedMetaData = getMetaDataFromAcc(t, cs, core.SystemAccountAddress, tokenIDs[i], shardID) + } require.Equal(t, newCreatorAddress.Bytes, retrievedMetaData.Creator) } @@ -1618,7 +1608,7 @@ func TestChainSimulator_ESDTModifyCreator_CrossShard(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[1].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[1].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -1695,8 +1685,13 @@ func TestChainSimulator_ESDTModifyCreator_CrossShard(t *testing.T) { require.Equal(t, "success", txResult.Status.String()) + retrievedMetaData := &esdt.MetaData{} shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(newCreatorAddress.Bytes) - retrievedMetaData := getMetaDataFromAcc(t, cs, core.SystemAccountAddress, tokenIDs[i], shardID) + if bytes.Equal(tokenIDs[i], nftTokenID) { + retrievedMetaData = getMetaDataFromAcc(t, cs, newCreatorAddress.Bytes, tokenIDs[i], shardID) + } else { + retrievedMetaData = getMetaDataFromAcc(t, cs, core.SystemAccountAddress, tokenIDs[i], shardID) + } require.Equal(t, newCreatorAddress.Bytes, retrievedMetaData.Creator) @@ -1813,7 +1808,7 @@ func TestChainSimulator_ESDTSetNewURIs(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -2015,7 +2010,7 @@ func TestChainSimulator_ESDTModifyRoyalties(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -2170,7 +2165,7 @@ func TestChainSimulator_NFT_ChangeToDynamicType(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[1].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[1].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -2276,34 +2271,7 @@ func testChainSimulatorChangeMetaData(t *testing.T, issueFn issueTxFunc) { metaData := txsFee.GetDefaultMetaData() metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - txDataField := bytes.Join( - [][]byte{ - []byte(core.BuiltInFunctionESDTNFTCreate), - []byte(hex.EncodeToString(tokenID)), - []byte(hex.EncodeToString(big.NewInt(2).Bytes())), // quantity - metaData.Name, - []byte(hex.EncodeToString(big.NewInt(10).Bytes())), - metaData.Hash, - metaData.Attributes, - metaData.Uris[0], - metaData.Uris[1], - metaData.Uris[2], - }, - []byte("@"), - ) - - tx = &transaction.Transaction{ - Nonce: nonce, - SndAddr: addrs[1].Bytes, - RcvAddr: addrs[1].Bytes, - GasLimit: 10_000_000, - GasPrice: minGasPrice, - Signature: []byte("dummySig"), - Data: txDataField, - Value: big.NewInt(0), - ChainID: []byte(configs.ChainID), - Version: 1, - } + tx = esdtNftCreateTx(nonce, addrs[1].Bytes, tokenID, metaData, 2) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -2321,6 +2289,9 @@ func testChainSimulatorChangeMetaData(t *testing.T, issueFn issueTxFunc) { require.NotNil(t, txResult) require.Equal(t, "success", txResult.Status.String()) + err = cs.GenerateBlocks(10) + require.Nil(t, err) + log.Info("Send to separate shards") tx = esdtNFTTransferTx(nonce, addrs[1].Bytes, addrs[2].Bytes, tokenID) @@ -2361,35 +2332,7 @@ func testChainSimulatorChangeMetaData(t *testing.T, issueFn issueTxFunc) { sftMetaData2.Hash = []byte(hex.EncodeToString([]byte("hash2"))) sftMetaData2.Attributes = []byte(hex.EncodeToString([]byte("attributes2"))) - txDataField = bytes.Join( - [][]byte{ - []byte(core.ESDTMetaDataUpdate), - []byte(hex.EncodeToString(tokenID)), - sftMetaData2.Nonce, - sftMetaData2.Name, - []byte(hex.EncodeToString(big.NewInt(10).Bytes())), - sftMetaData2.Hash, - sftMetaData2.Attributes, - sftMetaData2.Uris[0], - sftMetaData2.Uris[1], - sftMetaData2.Uris[2], - }, - []byte("@"), - ) - - tx = &transaction.Transaction{ - Nonce: 0, - SndAddr: addrs[0].Bytes, - RcvAddr: addrs[0].Bytes, - GasLimit: 10_000_000, - GasPrice: minGasPrice, - Signature: []byte("dummySig"), - Data: txDataField, - Value: big.NewInt(0), - ChainID: []byte(configs.ChainID), - Version: 1, - } - + tx = esdtMetaDataUpdateTx(tokenID, sftMetaData2, 0, addrs[0].Bytes) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) require.NotNil(t, txResult) @@ -2398,8 +2341,35 @@ func testChainSimulatorChangeMetaData(t *testing.T, issueFn issueTxFunc) { log.Info("Step 2. check that the newest metadata is saved") shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[0].Bytes) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, shardID, sftMetaData2) + + shard2ID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[2].Bytes) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, shard2ID, metaData) + + log.Info("Step 3. create new wallet is shard 2") + + mintValue := big.NewInt(10) + mintValue = mintValue.Mul(oneEGLD, mintValue) + newShard2Addr, err := cs.GenerateAndMintWalletAddress(2, mintValue) + require.Nil(t, err) + err = cs.GenerateBlocks(1) + require.Nil(t, err) + + log.Info("Step 4. send updated token to shard 2 ") + + tx = esdtNFTTransferTx(1, addrs[0].Bytes, newShard2Addr.Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + err = cs.GenerateBlocks(5) + require.Nil(t, err) + + log.Info("Step 5. check meta data in shard 2 is updated to latest version ") + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, shard2ID, sftMetaData2) checkMetaData(t, cs, core.SystemAccountAddress, tokenID, shardID, sftMetaData2) + } func TestChainSimulator_NFT_RegisterDynamic(t *testing.T) { @@ -2463,7 +2433,7 @@ func TestChainSimulator_NFT_RegisterDynamic(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -2476,7 +2446,8 @@ func TestChainSimulator_NFT_RegisterDynamic(t *testing.T) { shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[0].Bytes) - checkMetaData(t, cs, core.SystemAccountAddress, nftTokenID, shardID, nftMetaData) + checkMetaData(t, cs, addrs[0].Bytes, nftTokenID, shardID, nftMetaData) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, nftTokenID, shardID) log.Info("Check that token type is Dynamic") @@ -2559,7 +2530,7 @@ func TestChainSimulator_MetaESDT_RegisterDynamic(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -2706,7 +2677,7 @@ func TestChainSimulator_NFT_RegisterAndSetAllRolesDynamic(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -2719,7 +2690,8 @@ func TestChainSimulator_NFT_RegisterAndSetAllRolesDynamic(t *testing.T) { shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[0].Bytes) - checkMetaData(t, cs, core.SystemAccountAddress, nftTokenID, shardID, nftMetaData) + checkMetaData(t, cs, addrs[0].Bytes, nftTokenID, shardID, nftMetaData) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, nftTokenID, shardID) log.Info("Check that token type is Dynamic") @@ -2826,7 +2798,7 @@ func TestChainSimulator_SFT_RegisterAndSetAllRolesDynamic(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, sftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, sftTokenID, nftMetaData, 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -3001,7 +2973,7 @@ func TestChainSimulator_MetaESDT_RegisterAndSetAllRolesDynamic(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, metaTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, metaTokenID, nftMetaData, 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -3270,7 +3242,7 @@ func createTokenUpdateTokenIDAndTransfer( } setAddressEsdtRoles(t, cs, 1, walletWithRoles, tokenID, roles) - tx := nftCreateTx(2, originAddress, tokenID, metaData) + tx := esdtNftCreateTx(2, originAddress, tokenID, metaData, 1) txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -3395,7 +3367,7 @@ func TestChainSimulator_ChangeToDynamic_OldTokens(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -3418,7 +3390,7 @@ func TestChainSimulator_ChangeToDynamic_OldTokens(t *testing.T) { checkMetaData(t, cs, addrs[0].Bytes, metaESDTTokenID, shardID, esdtMetaData) checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, metaESDTTokenID, shardID) - err = cs.GenerateBlocksUntilEpochIsReached(int32(epochForDynamicNFT)) + err = cs.GenerateBlocksUntilEpochIsReached(epochForDynamicNFT) require.Nil(t, err) log.Info("Change to DYNAMIC type") @@ -3568,7 +3540,7 @@ func TestChainSimulator_CreateAndPause_NFT(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -3750,7 +3722,7 @@ func TestChainSimulator_CreateAndPauseTokens_DynamicNFT(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) @@ -3761,11 +3733,12 @@ func TestChainSimulator_CreateAndPauseTokens_DynamicNFT(t *testing.T) { err = cs.GenerateBlocks(10) require.Nil(t, err) - log.Info("Step 1. check that the metadata for all tokens is saved on the system account") + log.Info("Step 1. check that the metadata for the Dynamic NFT is saved on the user account") shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[0].Bytes) - checkMetaData(t, cs, core.SystemAccountAddress, nftTokenID, shardID, nftMetaData) + checkMetaData(t, cs, addrs[0].Bytes, nftTokenID, shardID, nftMetaData) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, nftTokenID, shardID) log.Info("Step 1b. Pause all tokens") @@ -3781,34 +3754,13 @@ func TestChainSimulator_CreateAndPauseTokens_DynamicNFT(t *testing.T) { require.Equal(t, "", result.ReturnMessage) require.Equal(t, testsChainSimulator.OkReturnCode, result.ReturnCode) - tx = updateTokenIDTx(nonce, addrs[0].Bytes, nftTokenID) - nonce++ - - log.Info("updating token id", "tokenID", nftTokenID) - - txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) - require.Nil(t, err) - require.NotNil(t, txResult) - require.Equal(t, "success", txResult.Status.String()) - - log.Info("change to dynamic token") - - tx = changeToDynamicTx(nonce, addrs[0].Bytes, nftTokenID) - nonce++ - - log.Info("updating token id", "tokenID", nftTokenID) - - txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) - require.Nil(t, err) - require.NotNil(t, txResult) - require.Equal(t, "success", txResult.Status.String()) - - log.Info("check that the metadata for all tokens is saved on the system account") + log.Info("check that the metadata for the Dynamic NFT is saved on the user account") err = cs.GenerateBlocks(10) require.Nil(t, err) - checkMetaData(t, cs, core.SystemAccountAddress, nftTokenID, shardID, nftMetaData) + checkMetaData(t, cs, addrs[0].Bytes, nftTokenID, shardID, nftMetaData) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, nftTokenID, shardID) log.Info("transfering token id", "tokenID", nftTokenID) @@ -3818,16 +3770,16 @@ func TestChainSimulator_CreateAndPauseTokens_DynamicNFT(t *testing.T) { require.NotNil(t, txResult) require.Equal(t, "success", txResult.Status.String()) - log.Info("check that the metaData for the NFT is still on the system account") + log.Info("check that the metaData for the NFT is on the new user account") err = cs.GenerateBlocks(10) require.Nil(t, err) shardID = cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[2].Bytes) - checkMetaData(t, cs, core.SystemAccountAddress, nftTokenID, shardID, nftMetaData) + checkMetaData(t, cs, addrs[1].Bytes, nftTokenID, shardID, nftMetaData) checkMetaDataNotInAcc(t, cs, addrs[0].Bytes, nftTokenID, shardID) - checkMetaDataNotInAcc(t, cs, addrs[1].Bytes, nftTokenID, shardID) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, nftTokenID, shardID) } func TestChainSimulator_CheckRolesWhichHasToBeSingular(t *testing.T) { @@ -3914,3 +3866,853 @@ func TestChainSimulator_CheckRolesWhichHasToBeSingular(t *testing.T) { } } } + +func TestChainSimulator_metaESDT_mergeMetaDataFromMultipleUpdates(t *testing.T) { + t.Parallel() + + baseIssuingCost := "1000" + cs, _ := getTestChainSimulatorWithDynamicNFTEnabled(t, baseIssuingCost) + defer cs.Close() + marshaller := cs.GetNodeHandler(0).GetCoreComponents().InternalMarshalizer() + addrs := createAddresses(t, cs, true) + + log.Info("Register dynamic metaESDT token") + + metaTicker := []byte("METATICKER") + metaTokenName := []byte("tokenName") + + decimals := big.NewInt(15) + txDataField := bytes.Join( + [][]byte{ + []byte("registerDynamic"), + []byte(hex.EncodeToString(metaTokenName)), + []byte(hex.EncodeToString(metaTicker)), + []byte(hex.EncodeToString([]byte("META"))), + []byte(hex.EncodeToString(decimals.Bytes())), + }, + []byte("@"), + ) + + callValue, _ := big.NewInt(0).SetString(baseIssuingCost, 10) + + shard0Nonce := uint64(0) + tx := &transaction.Transaction{ + Nonce: shard0Nonce, + SndAddr: addrs[0].Bytes, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 100_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: callValue, + ChainID: []byte(configs.ChainID), + Version: 1, + } + shard0Nonce++ + + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + + require.Equal(t, "success", txResult.Status.String()) + + tokenID := txResult.Logs.Events[0].Topics[0] + roles := [][]byte{ + []byte(core.ESDTRoleNFTCreate), + []byte(core.ESDTRoleNFTAddQuantity), + []byte(core.ESDTRoleTransfer), + []byte(core.ESDTRoleNFTUpdate), + } + setAddressEsdtRoles(t, cs, shard0Nonce, addrs[0], tokenID, roles) + shard0Nonce++ + + metaData := txsFee.GetDefaultMetaData() + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 2) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + shardID := cs.GetNodeHandler(0).GetProcessComponents().ShardCoordinator().ComputeId(addrs[0].Bytes) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, shardID, metaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, shardID, []byte{1}) + + log.Info("send metaEsdt cross shard") + + tx = esdtNFTTransferTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + log.Info("update metaData on shard 0") + + newMetaData := &txsFee.MetaData{} + newMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + newMetaData.Name = []byte(hex.EncodeToString([]byte("name2"))) + newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) + newMetaData.Attributes = []byte(hex.EncodeToString([]byte("attributes2"))) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData, shard0Nonce, addrs[0].Bytes) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + expectedMetaData := txsFee.GetDefaultMetaData() + expectedMetaData.Nonce = newMetaData.Nonce + expectedMetaData.Name = newMetaData.Name + expectedMetaData.Hash = newMetaData.Hash + expectedMetaData.Attributes = newMetaData.Attributes + + round := cs.GetNodeHandler(0).GetChainHandler().GetCurrentBlockHeader().GetRound() + reserved := &esdt.MetaDataVersion{ + Name: round, + Creator: round, + Hash: round, + Attributes: round, + } + firstVersion, _ := marshaller.Marshal(reserved) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, metaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, []byte{1}) + + log.Info("send the update role to shard 2") + + shard0Nonce = transferSpecialRoleToAddr(t, cs, shard0Nonce, tokenID, addrs[0].Bytes, addrs[2].Bytes, []byte(core.ESDTRoleNFTUpdate)) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + log.Info("update metaData on shard 2") + + newMetaData2 := &txsFee.MetaData{} + newMetaData2.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + newMetaData2.Uris = [][]byte{[]byte(hex.EncodeToString([]byte("uri5"))), []byte(hex.EncodeToString([]byte("uri6"))), []byte(hex.EncodeToString([]byte("uri7")))} + newMetaData2.Royalties = []byte(hex.EncodeToString(big.NewInt(15).Bytes())) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData2, 0, addrs[2].Bytes) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, metaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, []byte{1}) + + retrievedMetaData := getMetaDataFromAcc(t, cs, core.SystemAccountAddress, tokenID, 2) + require.Equal(t, uint64(1), retrievedMetaData.Nonce) + require.Equal(t, 0, len(retrievedMetaData.Name)) + require.Equal(t, addrs[2].Bytes, retrievedMetaData.Creator) + require.Equal(t, newMetaData2.Royalties, []byte(hex.EncodeToString(big.NewInt(int64(retrievedMetaData.Royalties)).Bytes()))) + require.Equal(t, 0, len(retrievedMetaData.Hash)) + require.Equal(t, 3, len(retrievedMetaData.URIs)) + for i, uri := range newMetaData2.Uris { + require.Equal(t, uri, []byte(hex.EncodeToString(retrievedMetaData.URIs[i]))) + } + require.Equal(t, 0, len(retrievedMetaData.Attributes)) + + round2 := cs.GetNodeHandler(2).GetChainHandler().GetCurrentBlockHeader().GetRound() + reserved = &esdt.MetaDataVersion{ + URIs: round2, + Creator: round2, + Royalties: round2, + } + secondVersion, _ := cs.GetNodeHandler(shardID).GetCoreComponents().InternalMarshalizer().Marshal(reserved) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 2, secondVersion) + + log.Info("transfer from shard 0 to shard 1 - should merge metaData") + + tx = esdtNFTTransferTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, firstVersion) + + log.Info("transfer from shard 1 to shard 2 - should merge metaData") + + tx = setSpecialRoleTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID, [][]byte{[]byte(core.ESDTRoleTransfer)}) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + shard0Nonce++ + + tx = esdtNFTTransferTx(0, addrs[1].Bytes, addrs[2].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, firstVersion) + + latestMetaData := txsFee.GetDefaultMetaData() + latestMetaData.Nonce = expectedMetaData.Nonce + latestMetaData.Name = expectedMetaData.Name + latestMetaData.Royalties = newMetaData2.Royalties + latestMetaData.Hash = expectedMetaData.Hash + latestMetaData.Attributes = expectedMetaData.Attributes + latestMetaData.Uris = newMetaData2.Uris + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 2, latestMetaData) + + reserved = &esdt.MetaDataVersion{ + Name: round, + Creator: round2, + Royalties: round2, + Hash: round, + URIs: round2, + Attributes: round, + } + thirdVersion, _ := cs.GetNodeHandler(shardID).GetCoreComponents().InternalMarshalizer().Marshal(reserved) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 2, thirdVersion) + + log.Info("transfer from shard 2 to shard 0 - should update metaData") + + tx = setSpecialRoleTx(shard0Nonce, addrs[0].Bytes, addrs[2].Bytes, tokenID, [][]byte{[]byte(core.ESDTRoleTransfer)}) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + tx = esdtNFTTransferTx(1, addrs[2].Bytes, addrs[0].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, latestMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, thirdVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 2, latestMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 2, thirdVersion) + + log.Info("transfer from shard 1 to shard 0 - liquidity should be updated") + + tx = esdtNFTTransferTx(1, addrs[1].Bytes, addrs[0].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 0, latestMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 0, thirdVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 1, expectedMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 1, firstVersion) + checkMetaData(t, cs, core.SystemAccountAddress, tokenID, 2, latestMetaData) + checkReservedField(t, cs, core.SystemAccountAddress, tokenID, 2, thirdVersion) +} + +func unsetSpecialRole( + nonce uint64, + sndAddr []byte, + address []byte, + token []byte, + role []byte, +) *transaction.Transaction { + txDataBytes := [][]byte{ + []byte("unSetSpecialRole"), + []byte(hex.EncodeToString(token)), + []byte(hex.EncodeToString(address)), + []byte(hex.EncodeToString(role)), + } + + txDataField := bytes.Join( + txDataBytes, + []byte("@"), + ) + + return &transaction.Transaction{ + Nonce: nonce, + SndAddr: sndAddr, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 60_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: big.NewInt(0), + ChainID: []byte(configs.ChainID), + Version: 1, + } +} + +func esdtMetaDataUpdateTx(tokenID []byte, metaData *txsFee.MetaData, nonce uint64, address []byte) *transaction.Transaction { + txData := [][]byte{ + []byte(core.ESDTMetaDataUpdate), + []byte(hex.EncodeToString(tokenID)), + metaData.Nonce, + metaData.Name, + metaData.Royalties, + metaData.Hash, + metaData.Attributes, + } + if len(metaData.Uris) > 0 { + txData = append(txData, metaData.Uris...) + } else { + txData = append(txData, nil) + } + + txDataField := bytes.Join( + txData, + []byte("@"), + ) + + tx := &transaction.Transaction{ + Nonce: nonce, + SndAddr: address, + RcvAddr: address, + GasLimit: 10_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: big.NewInt(0), + ChainID: []byte(configs.ChainID), + Version: 1, + } + + return tx +} + +func transferSpecialRoleToAddr( + t *testing.T, + cs testsChainSimulator.ChainSimulator, + nonce uint64, + tokenID []byte, + sndAddr []byte, + dstAddr []byte, + role []byte, +) uint64 { + tx := unsetSpecialRole(nonce, sndAddr, sndAddr, tokenID, role) + nonce++ + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + tx = setSpecialRoleTx(nonce, sndAddr, dstAddr, tokenID, [][]byte{role}) + nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + return nonce +} + +func TestChainSimulator_dynamicNFT_mergeMetaDataFromMultipleUpdates(t *testing.T) { + t.Parallel() + + baseIssuingCost := "1000" + cs, _ := getTestChainSimulatorWithDynamicNFTEnabled(t, baseIssuingCost) + defer cs.Close() + + addrs := createAddresses(t, cs, true) + + log.Info("Register dynamic NFT token") + + ticker := []byte("NFTTICKER") + tokenName := []byte("tokenName") + + txDataField := bytes.Join( + [][]byte{ + []byte("registerDynamic"), + []byte(hex.EncodeToString(tokenName)), + []byte(hex.EncodeToString(ticker)), + []byte(hex.EncodeToString([]byte("NFT"))), + }, + []byte("@"), + ) + + callValue, _ := big.NewInt(0).SetString(baseIssuingCost, 10) + + shard0Nonce := uint64(0) + tx := &transaction.Transaction{ + Nonce: shard0Nonce, + SndAddr: addrs[0].Bytes, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 100_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: callValue, + ChainID: []byte(configs.ChainID), + Version: 1, + } + shard0Nonce++ + + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + + require.Equal(t, "success", txResult.Status.String()) + + tokenID := txResult.Logs.Events[0].Topics[0] + roles := [][]byte{ + []byte(core.ESDTRoleNFTCreate), + []byte(core.ESDTRoleTransfer), + []byte(core.ESDTRoleNFTUpdate), + } + setAddressEsdtRoles(t, cs, shard0Nonce, addrs[0], tokenID, roles) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + metaData := txsFee.GetDefaultMetaData() + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 1) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaData(t, cs, addrs[0].Bytes, tokenID, 0, metaData) + + log.Info("give update role to another account and update metaData") + + shard0Nonce = transferSpecialRoleToAddr(t, cs, shard0Nonce, tokenID, addrs[0].Bytes, addrs[1].Bytes, []byte(core.ESDTRoleNFTUpdate)) + + newMetaData := &txsFee.MetaData{} + newMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + newMetaData.Name = []byte(hex.EncodeToString([]byte("name2"))) + newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) + newMetaData.Royalties = []byte(hex.EncodeToString(big.NewInt(15).Bytes())) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData, 0, addrs[1].Bytes) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaData(t, cs, addrs[0].Bytes, tokenID, 0, metaData) + newMetaData.Attributes = []byte{} + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, newMetaData) + + log.Info("transfer nft - should merge metaData") + + tx = esdtNFTTransferTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + mergedMetaData := txsFee.GetDefaultMetaData() + mergedMetaData.Nonce = metaData.Nonce + mergedMetaData.Name = newMetaData.Name + mergedMetaData.Hash = newMetaData.Hash + mergedMetaData.Royalties = newMetaData.Royalties + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaDataNotInAcc(t, cs, addrs[0].Bytes, tokenID, 0) + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, mergedMetaData) + + log.Info("transfer nft - should remove metaData from sender") + + tx = setSpecialRoleTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID, [][]byte{[]byte(core.ESDTRoleTransfer)}) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + tx = esdtNFTTransferTx(1, addrs[1].Bytes, addrs[2].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 2) + checkMetaDataNotInAcc(t, cs, addrs[0].Bytes, tokenID, 0) + checkMetaDataNotInAcc(t, cs, addrs[1].Bytes, tokenID, 1) + checkMetaData(t, cs, addrs[2].Bytes, tokenID, 2, mergedMetaData) +} + +func TestChainSimulator_dynamicNFT_changeMetaDataForOneNFTShouldNotChangeOtherNonces(t *testing.T) { + t.Parallel() + + baseIssuingCost := "1000" + cs, _ := getTestChainSimulatorWithDynamicNFTEnabled(t, baseIssuingCost) + defer cs.Close() + + addrs := createAddresses(t, cs, true) + + log.Info("Register dynamic NFT token") + + ticker := []byte("NFTTICKER") + tokenName := []byte("tokenName") + + txDataField := bytes.Join( + [][]byte{ + []byte("registerDynamic"), + []byte(hex.EncodeToString(tokenName)), + []byte(hex.EncodeToString(ticker)), + []byte(hex.EncodeToString([]byte("NFT"))), + }, + []byte("@"), + ) + + callValue, _ := big.NewInt(0).SetString(baseIssuingCost, 10) + + shard0Nonce := uint64(0) + tx := &transaction.Transaction{ + Nonce: shard0Nonce, + SndAddr: addrs[0].Bytes, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 100_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: callValue, + ChainID: []byte(configs.ChainID), + Version: 1, + } + shard0Nonce++ + + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + + require.Equal(t, "success", txResult.Status.String()) + + tokenID := txResult.Logs.Events[0].Topics[0] + roles := [][]byte{ + []byte(core.ESDTRoleNFTCreate), + []byte(core.ESDTRoleTransfer), + []byte(core.ESDTRoleNFTUpdate), + } + setAddressEsdtRoles(t, cs, shard0Nonce, addrs[0], tokenID, roles) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + metaData := txsFee.GetDefaultMetaData() + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 1) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(2).Bytes())) + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 1) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + log.Info("give update role to another account and update metaData for nonce 2") + + shard0Nonce = transferSpecialRoleToAddr(t, cs, shard0Nonce, tokenID, addrs[0].Bytes, addrs[1].Bytes, []byte(core.ESDTRoleNFTUpdate)) + + newMetaData := &txsFee.MetaData{} + newMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(2).Bytes())) + newMetaData.Name = []byte(hex.EncodeToString([]byte("name2"))) + newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) + newMetaData.Royalties = []byte(hex.EncodeToString(big.NewInt(15).Bytes())) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData, 0, addrs[1].Bytes) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + log.Info("transfer nft with nonce 1 - should not merge metaData") + + tx = esdtNFTTransferTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, metaData) +} + +func TestChainSimulator_dynamicNFT_updateBeforeCreateOnSameAccountShouldOverwrite(t *testing.T) { + t.Parallel() + + baseIssuingCost := "1000" + cs, _ := getTestChainSimulatorWithDynamicNFTEnabled(t, baseIssuingCost) + defer cs.Close() + + addrs := createAddresses(t, cs, true) + + log.Info("Register dynamic NFT token") + + ticker := []byte("NFTTICKER") + tokenName := []byte("tokenName") + + txDataField := bytes.Join( + [][]byte{ + []byte("registerDynamic"), + []byte(hex.EncodeToString(tokenName)), + []byte(hex.EncodeToString(ticker)), + []byte(hex.EncodeToString([]byte("NFT"))), + }, + []byte("@"), + ) + + callValue, _ := big.NewInt(0).SetString(baseIssuingCost, 10) + + shard0Nonce := uint64(0) + tx := &transaction.Transaction{ + Nonce: shard0Nonce, + SndAddr: addrs[0].Bytes, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 100_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: callValue, + ChainID: []byte(configs.ChainID), + Version: 1, + } + shard0Nonce++ + + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + + require.Equal(t, "success", txResult.Status.String()) + + tokenID := txResult.Logs.Events[0].Topics[0] + roles := [][]byte{ + []byte(core.ESDTRoleNFTCreate), + []byte(core.ESDTRoleTransfer), + []byte(core.ESDTRoleNFTUpdate), + } + setAddressEsdtRoles(t, cs, shard0Nonce, addrs[0], tokenID, roles) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + log.Info("update meta data for a token that is not yet created") + + newMetaData := &txsFee.MetaData{} + newMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + newMetaData.Name = []byte(hex.EncodeToString([]byte("name2"))) + newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) + newMetaData.Royalties = []byte(hex.EncodeToString(big.NewInt(15).Bytes())) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData, shard0Nonce, addrs[0].Bytes) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + newMetaData.Attributes = []byte{} + newMetaData.Uris = [][]byte{} + checkMetaData(t, cs, addrs[0].Bytes, tokenID, 0, newMetaData) + + log.Info("create nft with the same nonce - should overwrite the metadata") + + metaData := txsFee.GetDefaultMetaData() + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 1) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaData(t, cs, addrs[0].Bytes, tokenID, 0, metaData) +} + +func TestChainSimulator_dynamicNFT_updateBeforeCreateOnDifferentAccountsShouldMergeMetaDataWhenTransferred(t *testing.T) { + t.Parallel() + + baseIssuingCost := "1000" + cs, _ := getTestChainSimulatorWithDynamicNFTEnabled(t, baseIssuingCost) + defer cs.Close() + + addrs := createAddresses(t, cs, true) + + log.Info("Register dynamic NFT token") + + ticker := []byte("NFTTICKER") + tokenName := []byte("tokenName") + + txDataField := bytes.Join( + [][]byte{ + []byte("registerDynamic"), + []byte(hex.EncodeToString(tokenName)), + []byte(hex.EncodeToString(ticker)), + []byte(hex.EncodeToString([]byte("NFT"))), + }, + []byte("@"), + ) + + callValue, _ := big.NewInt(0).SetString(baseIssuingCost, 10) + + shard0Nonce := uint64(0) + tx := &transaction.Transaction{ + Nonce: shard0Nonce, + SndAddr: addrs[0].Bytes, + RcvAddr: vm.ESDTSCAddress, + GasLimit: 100_000_000, + GasPrice: minGasPrice, + Signature: []byte("dummySig"), + Data: txDataField, + Value: callValue, + ChainID: []byte(configs.ChainID), + Version: 1, + } + shard0Nonce++ + + txResult, err := cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + + require.Equal(t, "success", txResult.Status.String()) + + tokenID := txResult.Logs.Events[0].Topics[0] + roles := [][]byte{ + []byte(core.ESDTRoleNFTCreate), + []byte(core.ESDTRoleTransfer), + []byte(core.ESDTRoleNFTUpdate), + } + setAddressEsdtRoles(t, cs, shard0Nonce, addrs[0], tokenID, roles) + shard0Nonce++ + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + log.Info("transfer update role to another address") + + shard0Nonce = transferSpecialRoleToAddr(t, cs, shard0Nonce, tokenID, addrs[0].Bytes, addrs[1].Bytes, []byte(core.ESDTRoleNFTUpdate)) + + log.Info("update meta data for a token that is not yet created") + + newMetaData := &txsFee.MetaData{} + newMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + newMetaData.Name = []byte(hex.EncodeToString([]byte("name2"))) + newMetaData.Hash = []byte(hex.EncodeToString([]byte("hash2"))) + newMetaData.Royalties = []byte(hex.EncodeToString(big.NewInt(15).Bytes())) + + tx = esdtMetaDataUpdateTx(tokenID, newMetaData, 0, addrs[1].Bytes) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaDataNotInAcc(t, cs, addrs[0].Bytes, tokenID, 0) + newMetaData.Attributes = []byte{} + newMetaData.Uris = [][]byte{} + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, newMetaData) + + log.Info("create nft with the same nonce on different account") + + metaData := txsFee.GetDefaultMetaData() + metaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) + + tx = esdtNftCreateTx(shard0Nonce, addrs[0].Bytes, tokenID, metaData, 1) + shard0Nonce++ + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaData(t, cs, addrs[0].Bytes, tokenID, 0, metaData) + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, newMetaData) + + log.Info("transfer dynamic NFT to the updated account") + + tx = esdtNFTTransferTx(shard0Nonce, addrs[0].Bytes, addrs[1].Bytes, tokenID) + txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) + require.Nil(t, err) + require.NotNil(t, txResult) + require.Equal(t, "success", txResult.Status.String()) + + err = cs.GenerateBlocks(10) + require.Nil(t, err) + + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 0) + checkMetaDataNotInAcc(t, cs, core.SystemAccountAddress, tokenID, 1) + checkMetaDataNotInAcc(t, cs, addrs[0].Bytes, tokenID, 0) + newMetaData.Attributes = metaData.Attributes + newMetaData.Uris = metaData.Uris + checkMetaData(t, cs, addrs[1].Bytes, tokenID, 1, newMetaData) +} diff --git a/integrationTests/chainSimulator/vm/esdtTokens_test.go b/integrationTests/chainSimulator/vm/esdtTokens_test.go index d12bfcbb550..a5505de14ff 100644 --- a/integrationTests/chainSimulator/vm/esdtTokens_test.go +++ b/integrationTests/chainSimulator/vm/esdtTokens_test.go @@ -107,6 +107,11 @@ func TestChainSimulator_Api_TokenType(t *testing.T) { require.NotNil(t, txResult) require.Equal(t, "success", txResult.Status.String()) + scrs, err := cs.GetNodeHandler(core.MetachainShardId).GetFacadeHandler().GetSCRsByTxHash(txResult.Hash, txResult.SmartContractResults[0].Hash) + require.Nil(t, err) + require.NotNil(t, scrs) + require.Equal(t, len(txResult.SmartContractResults), len(scrs)) + nftTokenID := txResult.Logs.Events[0].Topics[0] setAddressEsdtRoles(t, cs, nonce, addrs[0], nftTokenID, roles) nonce++ @@ -149,7 +154,7 @@ func TestChainSimulator_Api_TokenType(t *testing.T) { } for i := range tokenIDs { - tx = nftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i]) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, tokenIDs[i], tokensMetadata[i], 1) txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) require.Nil(t, err) @@ -268,7 +273,7 @@ func TestChainSimulator_Api_NFTToken(t *testing.T) { nftMetaData := txsFee.GetDefaultMetaData() nftMetaData.Nonce = []byte(hex.EncodeToString(big.NewInt(1).Bytes())) - tx = nftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData) + tx = esdtNftCreateTx(nonce, addrs[0].Bytes, nftTokenID, nftMetaData, 1) nonce++ txResult, err = cs.SendTxAndGenerateBlockTilTxIsExecuted(tx, maxNumOfBlockToGenerateWhenExecutingTx) diff --git a/integrationTests/interface.go b/integrationTests/interface.go index e4be7fe388c..ad90ffbb6a3 100644 --- a/integrationTests/interface.go +++ b/integrationTests/interface.go @@ -118,5 +118,6 @@ type Facade interface { GetEligibleManagedKeys() ([]string, error) GetWaitingManagedKeys() ([]string, error) GetWaitingEpochsLeftForPublicKey(publicKey string) (uint32, error) + GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) IsInterfaceNil() bool } 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 c2bc8e5995c..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 { - epochsConfig.RelayedTransactionsV3EnableEpoch = integrationTests.UnreachableEpoch + 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 } @@ -89,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) @@ -112,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) @@ -123,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) @@ -237,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, @@ -278,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..41ece5b81eb 100644 --- a/integrationTests/multiShard/relayedTx/relayedTx_test.go +++ b/integrationTests/multiShard/relayedTx/relayedTx_test.go @@ -33,36 +33,32 @@ 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( 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() @@ -119,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() @@ -215,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() 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 ef55c21f54a..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,8 +3253,8 @@ func CreateEnableEpochsConfig() config.EnableEpochs { MiniBlockPartialExecutionEnableEpoch: UnreachableEpoch, RefactorPeersMiniBlocksEnableEpoch: UnreachableEpoch, SCProcessorV2EnableEpoch: UnreachableEpoch, - RelayedTransactionsV3EnableEpoch: UnreachableEpoch, FixRelayedBaseCostEnableEpoch: UnreachableEpoch, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: UnreachableEpoch, } } @@ -3362,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 b380a643660..b4e2490b900 100644 --- a/integrationTests/testProcessorNodeWithTestWebServer.go +++ b/integrationTests/testProcessorNodeWithTestWebServer.go @@ -24,6 +24,7 @@ import ( "github.com/multiversx/mx-chain-go/testscommon" "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/genesisMocks" + "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" "github.com/multiversx/mx-chain-go/testscommon/state" "github.com/multiversx/mx-chain-go/vm/systemSmartContracts/defaults" "github.com/multiversx/mx-chain-vm-common-go/parsers" @@ -162,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(), @@ -236,6 +236,8 @@ func createFacadeComponents(tpn *TestProcessorNode) nodeFacade.ApiResolver { TxTypeHandler: txTypeHandler, LogsFacade: logsFacade, DataFieldParser: dataFieldParser, + TxMarshaller: &marshallerMock.MarshalizerMock{}, + EnableEpochsHandler: tpn.EnableEpochsHandler, } apiTransactionHandler, err := transactionAPI.NewAPITransactionProcessor(argsApiTransactionProc) log.LogIfError(err) diff --git a/integrationTests/vm/testInitializer.go b/integrationTests/vm/testInitializer.go index fc129e36d90..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) @@ -629,6 +623,7 @@ func CreateVMAndBlockchainHookAndDataPool( blockChainHook, _ := vmFactory.BlockChainHookImpl().(*hooks.BlockChainHookImpl) _ = builtInFuncFactory.SetPayableHandler(blockChainHook) + _ = builtInFuncFactory.SetBlockchainHook(blockChainHook) return vmContainer, blockChainHook, datapool } @@ -809,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 - @@ -860,7 +854,6 @@ func CreateTxProcessorWithOneSCExecutorWithVMs( if err != nil { return nil, err } - _ = economicsData.SetTxTypeHandler(txTypeHandler) gasComp, err := preprocess.NewGasComputation(economicsData, txTypeHandler, enableEpochsHandler) if err != nil { @@ -872,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 { @@ -1330,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 } @@ -1944,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/txsFee/apiTransactionEvaluator_test.go b/integrationTests/vm/txsFee/apiTransactionEvaluator_test.go index 8f3894aa319..4c66bf28f52 100644 --- a/integrationTests/vm/txsFee/apiTransactionEvaluator_test.go +++ b/integrationTests/vm/txsFee/apiTransactionEvaluator_test.go @@ -142,7 +142,7 @@ func TestESDTTransfer(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) tx := utils.CreateESDTTransferTx(0, sndAddr, rcvAddr, token, big.NewInt(100), 0, 0) res, err := testContext.TxCostHandler.ComputeTransactionGasLimit(tx) @@ -170,7 +170,7 @@ func TestAsyncESDTTransfer(t *testing.T) { esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) // deploy 2 contracts ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) diff --git a/integrationTests/vm/txsFee/asyncCall_multi_test.go b/integrationTests/vm/txsFee/asyncCall_multi_test.go index 56a6dc02a26..ef14b5556a3 100644 --- a/integrationTests/vm/txsFee/asyncCall_multi_test.go +++ b/integrationTests/vm/txsFee/asyncCall_multi_test.go @@ -5,6 +5,7 @@ import ( "math/big" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/data/scheduled" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" @@ -276,7 +277,7 @@ func deployForwarderAndTestContract( forwarderSCAddress := utils.DoDeploySecond(t, testContext, pathToForwarder, ownerAccount, gasPrice, deployGasLimit, nil, big.NewInt(0)) - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, forwarderSCAddress, egldBalance, esdtToken, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, forwarderSCAddress, egldBalance, esdtToken, 0, esdtBalance, uint32(core.Fungible)) utils.CleanAccumulatedIntermediateTransactions(t, testContext) @@ -514,7 +515,7 @@ func transferESDTAndExecuteCrossShard(t *testing.T, numberOfCallsFromParent int, pathToContract = "testdata/forwarderQueue/forwarder-queue-promises.wasm" forwarderSCAddress := utils.DoDeploySecond(t, forwarderShard, pathToContract, forwarderOwnerAccount, gasPrice, gasLimit, nil, big.NewInt(0)) - utils.CreateAccountWithESDTBalance(t, forwarderShard.Accounts, forwarderSCAddress, egldBalance, esdtToken, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, forwarderShard.Accounts, forwarderSCAddress, egldBalance, esdtToken, 0, esdtBalance, uint32(core.Fungible)) utils.CheckESDTNFTBalance(t, forwarderShard, forwarderSCAddress, esdtToken, 0, esdtBalance) diff --git a/integrationTests/vm/txsFee/asyncESDT_test.go b/integrationTests/vm/txsFee/asyncESDT_test.go index c7c8d088fb9..32869f51ae9 100644 --- a/integrationTests/vm/txsFee/asyncESDT_test.go +++ b/integrationTests/vm/txsFee/asyncESDT_test.go @@ -40,7 +40,7 @@ func TestAsyncESDTCallShouldWork(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance, uint32(core.Fungible)) // deploy 2 contracts ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -96,7 +96,7 @@ func TestAsyncESDTCallSecondScRefusesPayment(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance, uint32(core.Fungible)) // deploy 2 contracts ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -153,7 +153,7 @@ func TestAsyncESDTCallsOutOfGas(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance, uint32(core.Fungible)) // deploy 2 contracts ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -208,7 +208,7 @@ func TestAsyncMultiTransferOnCallback(t *testing.T) { sftBalance := big.NewInt(1000) halfBalance := big.NewInt(500) - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance, uint32(core.SemiFungible)) utils.CheckESDTNFTBalance(t, testContext, ownerAddr, sftTokenID, sftNonce, sftBalance) ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -305,7 +305,7 @@ func TestAsyncMultiTransferOnCallAndOnCallback(t *testing.T) { sftBalance := big.NewInt(1000) halfBalance := big.NewInt(500) - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance, uint32(core.SemiFungible)) utils.CheckESDTNFTBalance(t, testContext, ownerAddr, sftTokenID, sftNonce, sftBalance) ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -408,7 +408,7 @@ func TestSendNFTToContractWith0Function(t *testing.T) { sftNonce := uint64(1) sftBalance := big.NewInt(1000) - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance, uint32(core.SemiFungible)) utils.CheckESDTNFTBalance(t, testContext, ownerAddr, sftTokenID, sftNonce, sftBalance) ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -461,7 +461,7 @@ func TestSendNFTToContractWith0FunctionNonPayable(t *testing.T) { sftNonce := uint64(1) sftBalance := big.NewInt(1000) - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, ownerAddr, big.NewInt(1000000000), sftTokenID, sftNonce, sftBalance, uint32(core.SemiFungible)) utils.CheckESDTNFTBalance(t, testContext, ownerAddr, sftTokenID, sftNonce, sftBalance) ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) @@ -523,7 +523,7 @@ func TestAsyncESDTCallForThirdContractShouldWork(t *testing.T) { localEsdtBalance := big.NewInt(100000000) esdtTransferValue := big.NewInt(5000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, localEgldBalance, token, 0, localEsdtBalance, uint32(core.Fungible)) // deploy contract ownerAccount, _ := testContext.Accounts.LoadAccount(ownerAddr) diff --git a/integrationTests/vm/txsFee/esdtLocalBurn_test.go b/integrationTests/vm/txsFee/esdtLocalBurn_test.go index 681c7e293b4..77edb13d0e2 100644 --- a/integrationTests/vm/txsFee/esdtLocalBurn_test.go +++ b/integrationTests/vm/txsFee/esdtLocalBurn_test.go @@ -95,7 +95,7 @@ func TestESDTLocalBurnNotAllowedShouldErr(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(40) tx := utils.CreateESDTLocalBurnTx(0, sndAddr, sndAddr, token, big.NewInt(100), gasPrice, gasLimit) diff --git a/integrationTests/vm/txsFee/esdtLocalMint_test.go b/integrationTests/vm/txsFee/esdtLocalMint_test.go index 516402c80a4..62d7bf5decf 100644 --- a/integrationTests/vm/txsFee/esdtLocalMint_test.go +++ b/integrationTests/vm/txsFee/esdtLocalMint_test.go @@ -61,7 +61,7 @@ func TestESDTLocalMintNotAllowedShouldErr(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(40) tx := utils.CreateESDTLocalMintTx(0, sndAddr, sndAddr, token, big.NewInt(100), gasPrice, gasLimit) diff --git a/integrationTests/vm/txsFee/esdtMetaDataRecreate_test.go b/integrationTests/vm/txsFee/esdtMetaDataRecreate_test.go index 8e46c5d613b..e2dc58caf8f 100644 --- a/integrationTests/vm/txsFee/esdtMetaDataRecreate_test.go +++ b/integrationTests/vm/txsFee/esdtMetaDataRecreate_test.go @@ -7,10 +7,12 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" + dataBlock "github.com/multiversx/mx-chain-core-go/data/block" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" "github.com/multiversx/mx-chain-go/integrationTests/vm/txsFee/utils" + "github.com/multiversx/mx-chain-go/process" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/stretchr/testify/require" ) @@ -35,6 +37,7 @@ func runEsdtMetaDataRecreateTest(t *testing.T, tokenType string) { testContext, err := vm.CreatePreparedTxProcessorWithVMs(config.EnableEpochs{}, 1) require.Nil(t, err) defer testContext.Close() + testContext.BlockchainHook.(process.BlockChainHookHandler).SetCurrentHeader(&dataBlock.Header{Round: 7}) createAccWithBalance(t, testContext.Accounts, sndAddr, big.NewInt(100000000)) createAccWithBalance(t, testContext.Accounts, core.ESDTSCAddress, big.NewInt(100000000)) @@ -61,7 +64,11 @@ func runEsdtMetaDataRecreateTest(t *testing.T, tokenType string) { _, err = testContext.Accounts.Commit() require.Nil(t, err) - checkMetaData(t, testContext, core.SystemAccountAddress, key, defaultMetaData) + if tokenType == core.DynamicNFTESDT { + checkMetaData(t, testContext, sndAddr, key, defaultMetaData) + } else { + checkMetaData(t, testContext, core.SystemAccountAddress, key, defaultMetaData) + } } func esdtMetaDataRecreateTx( diff --git a/integrationTests/vm/txsFee/esdtMetaDataUpdate_test.go b/integrationTests/vm/txsFee/esdtMetaDataUpdate_test.go index 53174e22a35..d8fc6c7bb19 100644 --- a/integrationTests/vm/txsFee/esdtMetaDataUpdate_test.go +++ b/integrationTests/vm/txsFee/esdtMetaDataUpdate_test.go @@ -7,10 +7,12 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" + dataBlock "github.com/multiversx/mx-chain-core-go/data/block" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" "github.com/multiversx/mx-chain-go/integrationTests/vm/txsFee/utils" + "github.com/multiversx/mx-chain-go/process" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/stretchr/testify/require" ) @@ -35,6 +37,7 @@ func runEsdtMetaDataUpdateTest(t *testing.T, tokenType string) { testContext, err := vm.CreatePreparedTxProcessorWithVMs(config.EnableEpochs{}, 1) require.Nil(t, err) defer testContext.Close() + testContext.BlockchainHook.(process.BlockChainHookHandler).SetCurrentHeader(&dataBlock.Header{Round: 7}) createAccWithBalance(t, testContext.Accounts, sndAddr, big.NewInt(100000000)) createAccWithBalance(t, testContext.Accounts, core.ESDTSCAddress, big.NewInt(100000000)) @@ -64,7 +67,11 @@ func runEsdtMetaDataUpdateTest(t *testing.T, tokenType string) { _, err = testContext.Accounts.Commit() require.Nil(t, err) - checkMetaData(t, testContext, core.SystemAccountAddress, key, defaultMetaData) + if tokenType == core.DynamicNFTESDT { + checkMetaData(t, testContext, sndAddr, key, defaultMetaData) + } else { + checkMetaData(t, testContext, core.SystemAccountAddress, key, defaultMetaData) + } } func esdtMetaDataUpdateTx( diff --git a/integrationTests/vm/txsFee/esdtModifyCreator_test.go b/integrationTests/vm/txsFee/esdtModifyCreator_test.go index ead51c5d61d..d12eb5186af 100644 --- a/integrationTests/vm/txsFee/esdtModifyCreator_test.go +++ b/integrationTests/vm/txsFee/esdtModifyCreator_test.go @@ -7,10 +7,13 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" + dataBlock "github.com/multiversx/mx-chain-core-go/data/block" + "github.com/multiversx/mx-chain-core-go/data/esdt" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" "github.com/multiversx/mx-chain-go/integrationTests/vm/txsFee/utils" + "github.com/multiversx/mx-chain-go/process" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/stretchr/testify/require" ) @@ -39,6 +42,7 @@ func runEsdtModifyCreatorTest(t *testing.T, tokenType string) { testContext, err := vm.CreatePreparedTxProcessorWithVMs(config.EnableEpochs{}, 1) require.Nil(t, err) defer testContext.Close() + testContext.BlockchainHook.(process.BlockChainHookHandler).SetCurrentHeader(&dataBlock.Header{Round: 7}) createAccWithBalance(t, testContext.Accounts, newCreator, big.NewInt(100000000)) createAccWithBalance(t, testContext.Accounts, creatorAddr, big.NewInt(100000000)) @@ -66,7 +70,12 @@ func runEsdtModifyCreatorTest(t *testing.T, tokenType string) { _, err = testContext.Accounts.Commit() require.Nil(t, err) - retrievedMetaData := getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + retrievedMetaData := &esdt.MetaData{} + if tokenType == core.DynamicNFTESDT { + retrievedMetaData = getMetaDataFromAcc(t, testContext, newCreator, key) + } else { + retrievedMetaData = getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + } require.Equal(t, newCreator, retrievedMetaData.Creator) } diff --git a/integrationTests/vm/txsFee/esdtModifyRoyalties_test.go b/integrationTests/vm/txsFee/esdtModifyRoyalties_test.go index f4ef7dc9f49..151f1a62866 100644 --- a/integrationTests/vm/txsFee/esdtModifyRoyalties_test.go +++ b/integrationTests/vm/txsFee/esdtModifyRoyalties_test.go @@ -7,10 +7,13 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" + dataBlock "github.com/multiversx/mx-chain-core-go/data/block" + "github.com/multiversx/mx-chain-core-go/data/esdt" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" "github.com/multiversx/mx-chain-go/integrationTests/vm/txsFee/utils" + "github.com/multiversx/mx-chain-go/process" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/stretchr/testify/require" ) @@ -34,6 +37,7 @@ func runEsdtModifyRoyaltiesTest(t *testing.T, tokenType string) { testContext, err := vm.CreatePreparedTxProcessorWithVMs(config.EnableEpochs{}, 1) require.Nil(t, err) defer testContext.Close() + testContext.BlockchainHook.(process.BlockChainHookHandler).SetCurrentHeader(&dataBlock.Header{Round: 7}) createAccWithBalance(t, testContext.Accounts, creatorAddr, big.NewInt(100000000)) createAccWithBalance(t, testContext.Accounts, core.ESDTSCAddress, big.NewInt(100000000)) @@ -60,7 +64,12 @@ func runEsdtModifyRoyaltiesTest(t *testing.T, tokenType string) { _, err = testContext.Accounts.Commit() require.Nil(t, err) - retrievedMetaData := getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + retrievedMetaData := &esdt.MetaData{} + if tokenType == core.DynamicNFTESDT { + retrievedMetaData = getMetaDataFromAcc(t, testContext, creatorAddr, key) + } else { + retrievedMetaData = getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + } require.Equal(t, uint32(big.NewInt(20).Uint64()), retrievedMetaData.Royalties) } diff --git a/integrationTests/vm/txsFee/esdtSetNewURIs_test.go b/integrationTests/vm/txsFee/esdtSetNewURIs_test.go index 66ec209c3ef..7c3500cd641 100644 --- a/integrationTests/vm/txsFee/esdtSetNewURIs_test.go +++ b/integrationTests/vm/txsFee/esdtSetNewURIs_test.go @@ -7,10 +7,13 @@ import ( "testing" "github.com/multiversx/mx-chain-core-go/core" + dataBlock "github.com/multiversx/mx-chain-core-go/data/block" + "github.com/multiversx/mx-chain-core-go/data/esdt" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" "github.com/multiversx/mx-chain-go/integrationTests/vm/txsFee/utils" + "github.com/multiversx/mx-chain-go/process" vmcommon "github.com/multiversx/mx-chain-vm-common-go" "github.com/stretchr/testify/require" ) @@ -35,6 +38,7 @@ func runEsdtSetNewURIsTest(t *testing.T, tokenType string) { testContext, err := vm.CreatePreparedTxProcessorWithVMs(config.EnableEpochs{}, 1) require.Nil(t, err) defer testContext.Close() + testContext.BlockchainHook.(process.BlockChainHookHandler).SetCurrentHeader(&dataBlock.Header{Round: 7}) createAccWithBalance(t, testContext.Accounts, sndAddr, big.NewInt(100000000)) createAccWithBalance(t, testContext.Accounts, core.ESDTSCAddress, big.NewInt(100000000)) @@ -61,7 +65,12 @@ func runEsdtSetNewURIsTest(t *testing.T, tokenType string) { _, err = testContext.Accounts.Commit() require.Nil(t, err) - retrievedMetaData := getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + retrievedMetaData := &esdt.MetaData{} + if tokenType == core.DynamicNFTESDT { + retrievedMetaData = getMetaDataFromAcc(t, testContext, sndAddr, key) + } else { + retrievedMetaData = getMetaDataFromAcc(t, testContext, core.SystemAccountAddress, key) + } require.Equal(t, [][]byte{[]byte("newUri1"), []byte("newUri2")}, retrievedMetaData.URIs) } diff --git a/integrationTests/vm/txsFee/esdt_test.go b/integrationTests/vm/txsFee/esdt_test.go index d51848762e8..54cf8b38b71 100644 --- a/integrationTests/vm/txsFee/esdt_test.go +++ b/integrationTests/vm/txsFee/esdt_test.go @@ -32,7 +32,7 @@ func TestESDTTransferShouldWork(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(40) tx := utils.CreateESDTTransferTx(0, sndAddr, rcvAddr, token, big.NewInt(100), gasPrice, gasLimit) @@ -72,7 +72,7 @@ func TestESDTTransferShouldWorkToMuchGasShouldConsumeAllGas(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(1000) tx := utils.CreateESDTTransferTx(0, sndAddr, rcvAddr, token, big.NewInt(100), gasPrice, gasLimit) @@ -112,7 +112,7 @@ func TestESDTTransferInvalidESDTValueShouldConsumeGas(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(1000) tx := utils.CreateESDTTransferTx(0, sndAddr, rcvAddr, token, big.NewInt(100000000+1), gasPrice, gasLimit) @@ -156,7 +156,7 @@ func TestESDTTransferCallBackOnErrorShouldNotGenerateSCRsFurther(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) hexEncodedToken := hex.EncodeToString(token) esdtValueEncoded := hex.EncodeToString(big.NewInt(100).Bytes()) diff --git a/integrationTests/vm/txsFee/multiESDTTransfer_test.go b/integrationTests/vm/txsFee/multiESDTTransfer_test.go index adaf89ad340..b9a4474cf34 100644 --- a/integrationTests/vm/txsFee/multiESDTTransfer_test.go +++ b/integrationTests/vm/txsFee/multiESDTTransfer_test.go @@ -4,6 +4,7 @@ import ( "math/big" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests/vm" @@ -29,9 +30,9 @@ func TestMultiESDTTransferShouldWork(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) secondToken := []byte("second") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), secondToken, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), secondToken, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(4000) tx := utils.CreateMultiTransferTX(0, sndAddr, rcvAddr, gasPrice, gasLimit, &utils.TransferESDTData{ @@ -90,9 +91,9 @@ func TestMultiESDTTransferFailsBecauseOfMaxLimit(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) secondToken := []byte("second") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), secondToken, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), secondToken, 0, esdtBalance, uint32(core.Fungible)) gasLimit := uint64(4000) tx := utils.CreateMultiTransferTX(0, sndAddr, rcvAddr, gasPrice, gasLimit, &utils.TransferESDTData{ diff --git a/integrationTests/vm/txsFee/multiShard/asyncESDT_test.go b/integrationTests/vm/txsFee/multiShard/asyncESDT_test.go index aa37bc6bf94..5ea878f2b26 100644 --- a/integrationTests/vm/txsFee/multiShard/asyncESDT_test.go +++ b/integrationTests/vm/txsFee/multiShard/asyncESDT_test.go @@ -5,6 +5,7 @@ import ( "math/big" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests" "github.com/multiversx/mx-chain-go/integrationTests/vm" @@ -46,7 +47,7 @@ func TestAsyncESDTTransferWithSCCallShouldWork(t *testing.T) { token := []byte("miiutoken") egldBalance := big.NewInt(10000000) esdtBalance := big.NewInt(10000000) - utils.CreateAccountWithESDTBalance(t, testContextSender.Accounts, senderAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContextSender.Accounts, senderAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) // create accounts for owners _, _ = vm.CreateAccount(testContextFirstContract.Accounts, firstContractOwner, 0, egldBalance) @@ -162,7 +163,7 @@ func TestAsyncESDTTransferWithSCCallSecondContractAnotherToken(t *testing.T) { token := []byte("miiutoken") egldBalance := big.NewInt(10000000) esdtBalance := big.NewInt(10000000) - utils.CreateAccountWithESDTBalance(t, testContextSender.Accounts, senderAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContextSender.Accounts, senderAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) // create accounts for owners _, _ = vm.CreateAccount(testContextFirstContract.Accounts, firstContractOwner, 0, egldBalance) diff --git a/integrationTests/vm/txsFee/multiShard/esdtLiquidity_test.go b/integrationTests/vm/txsFee/multiShard/esdtLiquidity_test.go index 6d2fe8cfa00..3e863713571 100644 --- a/integrationTests/vm/txsFee/multiShard/esdtLiquidity_test.go +++ b/integrationTests/vm/txsFee/multiShard/esdtLiquidity_test.go @@ -35,7 +35,7 @@ func TestSystemAccountLiquidityAfterCrossShardTransferAndBurn(t *testing.T) { _, _ = vm.CreateAccount(sh1Context.Accounts, sh1Addr, 0, big.NewInt(1000000000)) // create the nft and ensure that it exists on the account's trie and the liquidity is set on the system account - utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID, 1, big.NewInt(1)) + utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID, 1, big.NewInt(1), uint32(core.NonFungible)) utils.CheckESDTNFTBalance(t, sh0Context, sh0Addr, tokenID, 1, big.NewInt(1)) utils.CheckESDTNFTBalance(t, sh0Context, core.SystemAccountAddress, tokenID, 1, big.NewInt(1)) @@ -86,7 +86,7 @@ func TestSystemAccountLiquidityAfterNFTWipe(t *testing.T) { defer metaContext.Close() // create the nft and ensure that it exists on the account's trie and the liquidity is set on the system account - utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(10000000000000), tokenID, 1, big.NewInt(1)) + utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(10000000000000), tokenID, 1, big.NewInt(1), uint32(core.NonFungible)) utils.CheckESDTNFTBalance(t, sh0Context, sh0Addr, tokenID, 1, big.NewInt(1)) utils.CheckESDTNFTBalance(t, sh0Context, core.SystemAccountAddress, tokenID, 1, big.NewInt(1)) @@ -136,7 +136,7 @@ func TestSystemAccountLiquidityAfterSFTWipe(t *testing.T) { defer metaContext.Close() // create the nft and ensure that it exists on the account's trie and the liquidity is set on the system account - utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(10000000000000), tokenID, 1, big.NewInt(10)) + utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(10000000000000), tokenID, 1, big.NewInt(10), uint32(core.SemiFungible)) utils.CheckESDTNFTBalance(t, sh0Context, sh0Addr, tokenID, 1, big.NewInt(10)) utils.CheckESDTNFTBalance(t, sh0Context, core.SystemAccountAddress, tokenID, 1, big.NewInt(10)) diff --git a/integrationTests/vm/txsFee/multiShard/esdt_test.go b/integrationTests/vm/txsFee/multiShard/esdt_test.go index 9dd828eb8c1..2e37f2c9948 100644 --- a/integrationTests/vm/txsFee/multiShard/esdt_test.go +++ b/integrationTests/vm/txsFee/multiShard/esdt_test.go @@ -33,7 +33,7 @@ func TestESDTTransferShouldWork(t *testing.T) { egldBalance := big.NewInt(100000000) esdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, egldBalance, token, 0, esdtBalance, uint32(core.Fungible)) gasPrice := uint64(10) gasLimit := uint64(40) @@ -73,8 +73,8 @@ func TestMultiESDTNFTTransferViaRelayedV2(t *testing.T) { _, _ = vm.CreateAccount(sh1Context.Accounts, relayerSh1, 0, big.NewInt(1000000000)) // create the nfts, add the liquidity to the system accounts and check for balances - utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID1, 1, big.NewInt(1)) - utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID2, 1, big.NewInt(1)) + utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID1, 1, big.NewInt(1), uint32(core.NonFungible)) + utils.CreateAccountWithESDTBalance(t, sh0Context.Accounts, sh0Addr, big.NewInt(100000000), tokenID2, 1, big.NewInt(1), uint32(core.NonFungible)) sh0Accnt, _ := sh0Context.Accounts.LoadAccount(sh0Addr) sh1Accnt, _ := sh1Context.Accounts.LoadAccount(sh1Addr) diff --git a/integrationTests/vm/txsFee/relayedAsyncESDT_test.go b/integrationTests/vm/txsFee/relayedAsyncESDT_test.go index bb8b05606a7..9958dc2e6b2 100644 --- a/integrationTests/vm/txsFee/relayedAsyncESDT_test.go +++ b/integrationTests/vm/txsFee/relayedAsyncESDT_test.go @@ -5,6 +5,7 @@ import ( "math/big" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests" "github.com/multiversx/mx-chain-go/integrationTests/vm" @@ -34,7 +35,7 @@ func TestRelayedAsyncESDTCallShouldWork(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance, uint32(core.Fungible)) _, _ = vm.CreateAccount(testContext.Accounts, relayerAddr, 0, localEgldBalance) // deploy 2 contracts @@ -96,7 +97,7 @@ func TestRelayedAsyncESDTCall_InvalidCallFirstContract(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance, uint32(core.Fungible)) _, _ = vm.CreateAccount(testContext.Accounts, relayerAddr, 0, localEgldBalance) // deploy 2 contracts @@ -158,7 +159,7 @@ func TestRelayedAsyncESDTCall_InvalidOutOfGas(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance, uint32(core.Fungible)) _, _ = vm.CreateAccount(testContext.Accounts, relayerAddr, 0, localEgldBalance) // deploy 2 contracts diff --git a/integrationTests/vm/txsFee/relayedESDT_test.go b/integrationTests/vm/txsFee/relayedESDT_test.go index 55a7e1bde04..ffe9597f943 100644 --- a/integrationTests/vm/txsFee/relayedESDT_test.go +++ b/integrationTests/vm/txsFee/relayedESDT_test.go @@ -4,6 +4,7 @@ import ( "math/big" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-go/config" "github.com/multiversx/mx-chain-go/integrationTests" "github.com/multiversx/mx-chain-go/integrationTests/vm" @@ -40,7 +41,7 @@ func testRelayedESDTTransferShouldWork( relayerBalance := big.NewInt(10000000) localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance, uint32(core.Fungible)) _, _ = vm.CreateAccount(testContext.Accounts, relayerAddr, 0, relayerBalance) gasLimit := uint64(40) @@ -102,7 +103,7 @@ func testRelayedESTTransferNotEnoughESTValueShouldConsumeGas( relayerBalance := big.NewInt(10000000) localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, big.NewInt(0), token, 0, localEsdtBalance, uint32(core.Fungible)) _, _ = vm.CreateAccount(testContext.Accounts, relayerAddr, 0, relayerBalance) gasLimit := uint64(42) diff --git a/integrationTests/vm/txsFee/scCalls_test.go b/integrationTests/vm/txsFee/scCalls_test.go index c17474eb9e3..c98d0960b66 100644 --- a/integrationTests/vm/txsFee/scCalls_test.go +++ b/integrationTests/vm/txsFee/scCalls_test.go @@ -352,7 +352,7 @@ func TestESDTScCallAndGasChangeShouldWork(t *testing.T) { localEsdtBalance := big.NewInt(100000000) token := []byte("miiutoken") - utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, senderBalance, token, 0, localEsdtBalance) + utils.CreateAccountWithESDTBalance(t, testContext.Accounts, sndAddr, senderBalance, token, 0, localEsdtBalance, uint32(core.Fungible)) txData := txDataBuilder.NewBuilder() valueToSendToSc := int64(1000) diff --git a/integrationTests/vm/txsFee/utils/utilsESDT.go b/integrationTests/vm/txsFee/utils/utilsESDT.go index 68fe255a1ba..99428ecfcf7 100644 --- a/integrationTests/vm/txsFee/utils/utilsESDT.go +++ b/integrationTests/vm/txsFee/utils/utilsESDT.go @@ -27,6 +27,7 @@ func CreateAccountWithESDTBalance( tokenIdentifier []byte, esdtNonce uint64, esdtValue *big.Int, + esdtType uint32, ) { account, err := accnts.LoadAccount(pubKey) require.Nil(t, err) @@ -39,6 +40,7 @@ func CreateAccountWithESDTBalance( require.Nil(t, err) esdtData := &esdt.ESDigitalToken{ + Type: esdtType, Value: esdtValue, Properties: []byte{}, } @@ -92,6 +94,7 @@ func CreateAccountWithNFT( require.Nil(t, err) esdtData := &esdt.ESDigitalToken{ + Type: uint32(core.NonFungible), Value: big.NewInt(1), Properties: []byte{}, TokenMetaData: &esdt.MetaData{ @@ -152,7 +155,7 @@ func CreateAccountWithESDTBalanceAndRoles( esdtValue *big.Int, roles [][]byte, ) { - CreateAccountWithESDTBalance(t, accnts, pubKey, egldValue, tokenIdentifier, esdtNonce, esdtValue) + CreateAccountWithESDTBalance(t, accnts, pubKey, egldValue, tokenIdentifier, esdtNonce, esdtValue, uint32(core.Fungible)) SetESDTRoles(t, accnts, pubKey, tokenIdentifier, roles) } 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/mockcontracts/simpleChildSC.go b/integrationTests/vm/wasm/wasmvm/mockcontracts/simpleChildSC.go deleted file mode 100644 index 7e1bb9dbaf5..00000000000 --- a/integrationTests/vm/wasm/wasmvm/mockcontracts/simpleChildSC.go +++ /dev/null @@ -1,50 +0,0 @@ -package mockcontracts - -import ( - "errors" - - mock "github.com/multiversx/mx-chain-vm-go/mock/context" - test "github.com/multiversx/mx-chain-vm-go/testcommon" - "github.com/multiversx/mx-chain-vm-go/vmhost" -) - -// SimpleCallChildMock is an exposed mock contract method -func SimpleCallChildMock(instanceMock *mock.InstanceMock, config interface{}) { - instanceMock.AddMockMethod("simpleChildFunction", func() *mock.InstanceMock { - testConfig := config.(*test.TestConfig) - host := instanceMock.Host - instance := mock.GetMockInstance(host) - - arguments := host.Runtime().Arguments() - if len(arguments) != 1 { - host.Runtime().SignalUserError("wrong num of arguments") - return instance - } - - host.Metering().UseGas(testConfig.GasUsedByChild) - - behavior := byte(0) - if len(arguments[0]) != 0 { - behavior = arguments[0][0] - } - err := handleChildBehaviorArgument(host, behavior) - if err != nil { - return instance - } - - _, _ = host.Storage().SetStorage(test.ChildKey, test.ChildData) - host.Output().Finish(test.ChildFinish) - - return instance - }) -} - -func handleChildBehaviorArgument(host vmhost.VMHost, behavior byte) error { - if behavior == 1 { - host.Runtime().SignalUserError("child error") - return errors.New("behavior / child error") - } - - host.Output().Finish([]byte{behavior}) - return nil -} diff --git a/integrationTests/vm/wasm/wasmvm/mockcontracts/simpleParentSC.go b/integrationTests/vm/wasm/wasmvm/mockcontracts/simpleParentSC.go deleted file mode 100644 index 63f4fcc5d4e..00000000000 --- a/integrationTests/vm/wasm/wasmvm/mockcontracts/simpleParentSC.go +++ /dev/null @@ -1,43 +0,0 @@ -package mockcontracts - -import ( - "math/big" - - mock "github.com/multiversx/mx-chain-vm-go/mock/context" - test "github.com/multiversx/mx-chain-vm-go/testcommon" - "github.com/multiversx/mx-chain-vm-go/vmhost" - "github.com/multiversx/mx-chain-vm-go/vmhost/vmhooks" - "github.com/stretchr/testify/require" -) - -var failBehavior = []byte{1} - -// PerformOnDestCallFailParentMock is an exposed mock contract method -func PerformOnDestCallFailParentMock(instanceMock *mock.InstanceMock, config interface{}) { - instanceMock.AddMockMethod("performOnDestCallFail", func() *mock.InstanceMock { - testConfig := config.(*test.TestConfig) - host := instanceMock.Host - instance := mock.GetMockInstance(host) - t := instance.T - - err := host.Metering().UseGasBounded(testConfig.GasUsedByParent) - if err != nil { - host.Runtime().SetRuntimeBreakpointValue(vmhost.BreakpointOutOfGas) - return instance - } - - _, _ = host.Storage().SetStorage(test.ParentKeyA, test.ParentDataA) - host.Output().Finish(test.ParentFinishA) - - retVal := vmhooks.ExecuteOnDestContextWithTypedArgs( - host, - int64(testConfig.GasProvidedToChild), - big.NewInt(0), - []byte("simpleChildFunction"), - testConfig.ChildAddress, - [][]byte{failBehavior}) - require.Equal(t, retVal, int32(1)) - - return instance - }) -} 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/memoryComponents.go b/node/chainSimulator/components/memoryComponents.go index 3b12e720756..639dafc753d 100644 --- a/node/chainSimulator/components/memoryComponents.go +++ b/node/chainSimulator/components/memoryComponents.go @@ -9,11 +9,11 @@ import ( // CreateMemUnit creates a new in-memory storage unit func CreateMemUnit() storage.Storer { - capacity := uint32(10) + capacity := uint32(10_000_000) shards := uint32(1) sizeInBytes := uint64(0) cache, _ := storageunit.NewCache(storageunit.CacheConfig{Type: storageunit.LRUCache, Capacity: capacity, Shards: shards, SizeInBytes: sizeInBytes}) - persist, _ := database.NewlruDB(100000) + persist, _ := database.NewlruDB(10_000_000) unit, _ := storageunit.NewStorageUnit(cache, persist) return unit 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..f884d8d32c9 100644 --- a/node/external/dtos.go +++ b/node/external/dtos.go @@ -1,24 +1,20 @@ 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 } diff --git a/node/external/interface.go b/node/external/interface.go index a12ef177ce1..e70367e201d 100644 --- a/node/external/interface.go +++ b/node/external/interface.go @@ -61,6 +61,7 @@ type DelegatedListHandler interface { // APITransactionHandler defines what an API transaction handler should be able to do type APITransactionHandler interface { GetTransaction(txHash string, withResults bool) (*transaction.ApiTransactionResult, error) + GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) GetTransactionsPool(fields string) (*common.TransactionsPoolAPIResponse, error) GetTransactionsPoolForSender(sender, fields string) (*common.TransactionsPoolForSenderApiResponse, error) GetLastPoolNonceForSender(sender string) (uint64, error) diff --git a/node/external/nodeApiResolver.go b/node/external/nodeApiResolver.go index 0ae0356f4f7..7f1bd2269b4 100644 --- a/node/external/nodeApiResolver.go +++ b/node/external/nodeApiResolver.go @@ -189,6 +189,11 @@ func (nar *nodeApiResolver) GetTransaction(hash string, withResults bool) (*tran return nar.apiTransactionHandler.GetTransaction(hash, withResults) } +// GetSCRsByTxHash will return a list of smart contract results based on a provided tx hash and smart contract result hash +func (nar *nodeApiResolver) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + return nar.apiTransactionHandler.GetSCRsByTxHash(txHash, scrHash) +} + // GetTransactionsPool will return a structure containing the transactions pool that is to be returned on API calls func (nar *nodeApiResolver) GetTransactionsPool(fields string) (*common.TransactionsPoolAPIResponse, error) { return nar.apiTransactionHandler.GetTransactionsPool(fields) diff --git a/node/external/transactionAPI/apiTransactionArgs.go b/node/external/transactionAPI/apiTransactionArgs.go index bb1aa10a659..1e4099390fd 100644 --- a/node/external/transactionAPI/apiTransactionArgs.go +++ b/node/external/transactionAPI/apiTransactionArgs.go @@ -6,6 +6,7 @@ import ( "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/data/typeConverters" "github.com/multiversx/mx-chain-core-go/marshal" + "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/dataRetriever" "github.com/multiversx/mx-chain-go/dblookupext" "github.com/multiversx/mx-chain-go/process" @@ -27,4 +28,6 @@ type ArgAPITransactionProcessor struct { TxTypeHandler process.TxTypeHandler LogsFacade LogsFacade DataFieldParser DataFieldParser + TxMarshaller marshal.Marshalizer + EnableEpochsHandler common.EnableEpochsHandler } diff --git a/node/external/transactionAPI/apiTransactionProcessor.go b/node/external/transactionAPI/apiTransactionProcessor.go index b12aa9ac86f..c67ad1cb445 100644 --- a/node/external/transactionAPI/apiTransactionProcessor.go +++ b/node/external/transactionAPI/apiTransactionProcessor.go @@ -2,6 +2,7 @@ package transactionAPI import ( "encoding/hex" + "errors" "fmt" "sort" "strings" @@ -19,6 +20,7 @@ import ( "github.com/multiversx/mx-chain-go/dataRetriever" "github.com/multiversx/mx-chain-go/dblookupext" "github.com/multiversx/mx-chain-go/process" + "github.com/multiversx/mx-chain-go/process/smartContract" "github.com/multiversx/mx-chain-go/process/txstatus" "github.com/multiversx/mx-chain-go/sharding" "github.com/multiversx/mx-chain-go/storage/txcache" @@ -43,6 +45,7 @@ type apiTransactionProcessor struct { transactionResultsProcessor *apiTransactionResultsProcessor refundDetector *refundDetector gasUsedAndFeeProcessor *gasUsedAndFeeProcessor + enableEpochsHandler common.EnableEpochsHandler } // NewAPITransactionProcessor will create a new instance of apiTransactionProcessor @@ -65,7 +68,13 @@ func NewAPITransactionProcessor(args *ArgAPITransactionProcessor) (*apiTransacti ) refundDetectorInstance := NewRefundDetector() - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(args.FeeComputer, args.AddressPubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + args.FeeComputer, + args.AddressPubKeyConverter, + smartContract.NewArgumentParser(), + args.TxMarshaller, + args.EnableEpochsHandler, + ) return &apiTransactionProcessor{ roundDuration: args.RoundDuration, @@ -83,9 +92,53 @@ func NewAPITransactionProcessor(args *ArgAPITransactionProcessor) (*apiTransacti transactionResultsProcessor: txResultsProc, refundDetector: refundDetectorInstance, gasUsedAndFeeProcessor: gasUsedAndFeeProc, + enableEpochsHandler: args.EnableEpochsHandler, }, nil } +// GetSCRsByTxHash will return a list of smart contract results based on a provided tx hash and smart contract result hash +func (atp *apiTransactionProcessor) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + decodedScrHash, err := hex.DecodeString(scrHash) + if err != nil { + return nil, err + } + + decodedTxHash, err := hex.DecodeString(txHash) + if err != nil { + return nil, err + } + + if !atp.historyRepository.IsEnabled() { + return nil, fmt.Errorf("cannot return smat contract results: %w", ErrDBLookExtensionIsNotEnabled) + } + + miniblockMetadata, err := atp.historyRepository.GetMiniblockMetadataByTxHash(decodedScrHash) + if err != nil { + return nil, fmt.Errorf("%s: %w", ErrTransactionNotFound.Error(), err) + } + + resultsHashes, err := atp.historyRepository.GetResultsHashesByTxHash(decodedTxHash, miniblockMetadata.Epoch) + if err != nil { + // It's perfectly normal to have transactions without SCRs. + if errors.Is(err, dblookupext.ErrNotFoundInStorage) { + return []*transaction.ApiSmartContractResult{}, nil + } + return nil, err + } + + scrsAPI := make([]*transaction.ApiSmartContractResult, 0, len(resultsHashes.ScResultsHashesAndEpoch)) + for _, scrHashesEpoch := range resultsHashes.ScResultsHashesAndEpoch { + scrs, errGet := atp.transactionResultsProcessor.getSmartContractResultsInTransactionByHashesAndEpoch(scrHashesEpoch.ScResultsHashes, scrHashesEpoch.Epoch) + if errGet != nil { + return nil, errGet + } + + scrsAPI = append(scrsAPI, scrs...) + } + + return scrsAPI, nil +} + // GetTransaction gets the transaction based on the given hash. It will search in the cache and the storage and // will return the transaction in a format which can be respected by all types of transactions (normal, reward or unsigned) func (atp *apiTransactionProcessor) GetTransaction(txHash string, withResults bool) (*transaction.ApiTransactionResult, error) { @@ -144,6 +197,13 @@ func (atp *apiTransactionProcessor) populateComputedFieldInitiallyPaidFee(tx *tr fee := atp.feeComputer.ComputeTransactionFee(tx) // For user-initiated transactions, we can assume the fee is always strictly positive (note: BigInt(0) is stringified as ""). tx.InitiallyPaidFee = fee.String() + + isFeeFixActive := atp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) + isRelayedAfterFix := tx.IsRelayed && isFeeFixActive + if isRelayedAfterFix { + _, fee, _ = atp.gasUsedAndFeeProcessor.getFeeOfRelayed(tx) + tx.InitiallyPaidFee = fee.String() + } } func (atp *apiTransactionProcessor) populateComputedFieldIsRefund(tx *transaction.ApiTransactionResult) { diff --git a/node/external/transactionAPI/apiTransactionProcessor_test.go b/node/external/transactionAPI/apiTransactionProcessor_test.go index 7d86a1610c5..e6a7040fe87 100644 --- a/node/external/transactionAPI/apiTransactionProcessor_test.go +++ b/node/external/transactionAPI/apiTransactionProcessor_test.go @@ -32,7 +32,9 @@ import ( "github.com/multiversx/mx-chain-go/testscommon" dataRetrieverMock "github.com/multiversx/mx-chain-go/testscommon/dataRetriever" dblookupextMock "github.com/multiversx/mx-chain-go/testscommon/dblookupext" + "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/genericMocks" + "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" storageStubs "github.com/multiversx/mx-chain-go/testscommon/storage" "github.com/multiversx/mx-chain-go/testscommon/txcachemocks" datafield "github.com/multiversx/mx-chain-vm-common-go/parsers/dataField" @@ -59,6 +61,8 @@ func createMockArgAPITransactionProcessor() *ArgAPITransactionProcessor { return &datafield.ResponseParseData{} }, }, + TxMarshaller: &marshallerMock.MarshalizerMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), } } @@ -181,6 +185,24 @@ func TestNewAPITransactionProcessor(t *testing.T) { _, err := NewAPITransactionProcessor(arguments) require.Equal(t, ErrNilDataFieldParser, err) }) + t.Run("NilTxMarshaller", func(t *testing.T) { + t.Parallel() + + arguments := createMockArgAPITransactionProcessor() + arguments.TxMarshaller = nil + + _, err := NewAPITransactionProcessor(arguments) + require.True(t, strings.Contains(err.Error(), process.ErrNilMarshalizer.Error())) + }) + t.Run("NilEnableEpochsHandler", func(t *testing.T) { + t.Parallel() + + arguments := createMockArgAPITransactionProcessor() + arguments.EnableEpochsHandler = nil + + _, err := NewAPITransactionProcessor(arguments) + require.Equal(t, process.ErrNilEnableEpochsHandler, err) + }) } func TestNode_GetTransactionInvalidHashShouldErr(t *testing.T) { @@ -268,6 +290,95 @@ func TestNode_GetTransactionFromPool(t *testing.T) { require.Equal(t, transaction.TxStatusPending, actualG.Status) } +func TestNode_GetSCRs(t *testing.T) { + scResultHash := []byte("scHash") + txHash := []byte("txHash") + + marshalizer := &mock.MarshalizerFake{} + scResult := &smartContractResult.SmartContractResult{ + Nonce: 1, + SndAddr: []byte("snd"), + RcvAddr: []byte("rcv"), + OriginalTxHash: txHash, + Data: []byte("test"), + } + + resultHashesByTxHash := &dblookupext.ResultsHashesByTxHash{ + ScResultsHashesAndEpoch: []*dblookupext.ScResultsHashesAndEpoch{ + { + Epoch: 0, + ScResultsHashes: [][]byte{scResultHash}, + }, + }, + } + + chainStorer := &storageStubs.ChainStorerStub{ + GetStorerCalled: func(unitType dataRetriever.UnitType) (storage.Storer, error) { + switch unitType { + case dataRetriever.UnsignedTransactionUnit: + return &storageStubs.StorerStub{ + GetFromEpochCalled: func(key []byte, epoch uint32) ([]byte, error) { + return marshalizer.Marshal(scResult) + }, + }, nil + default: + return nil, storage.ErrKeyNotFound + } + }, + } + + historyRepo := &dblookupextMock.HistoryRepositoryStub{ + GetMiniblockMetadataByTxHashCalled: func(hash []byte) (*dblookupext.MiniblockMetadata, error) { + return &dblookupext.MiniblockMetadata{}, nil + }, + GetEventsHashesByTxHashCalled: func(hash []byte, epoch uint32) (*dblookupext.ResultsHashesByTxHash, error) { + return resultHashesByTxHash, nil + }, + } + + feeComp := &testscommon.FeeComputerStub{ + ComputeTransactionFeeCalled: func(tx *transaction.ApiTransactionResult) *big.Int { + return big.NewInt(1000) + }, + } + + args := &ArgAPITransactionProcessor{ + RoundDuration: 0, + GenesisTime: time.Time{}, + Marshalizer: &mock.MarshalizerFake{}, + AddressPubKeyConverter: &testscommon.PubkeyConverterMock{}, + ShardCoordinator: &mock.ShardCoordinatorMock{}, + HistoryRepository: historyRepo, + StorageService: chainStorer, + DataPool: dataRetrieverMock.NewPoolsHolderMock(), + Uint64ByteSliceConverter: mock.NewNonceHashConverterMock(), + FeeComputer: feeComp, + TxTypeHandler: &testscommon.TxTypeHandlerMock{}, + LogsFacade: &testscommon.LogsFacadeStub{}, + DataFieldParser: &testscommon.DataFieldParserStub{ + ParseCalled: func(dataField []byte, sender, receiver []byte, _ uint32) *datafield.ResponseParseData { + return &datafield.ResponseParseData{} + }, + }, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + TxMarshaller: &mock.MarshalizerFake{}, + } + apiTransactionProc, _ := NewAPITransactionProcessor(args) + + scrs, err := apiTransactionProc.GetSCRsByTxHash(hex.EncodeToString(txHash), hex.EncodeToString(scResultHash)) + require.Nil(t, err) + require.Equal(t, 1, len(scrs)) + require.Equal(t, &transaction.ApiSmartContractResult{ + Nonce: 1, + Data: "test", + Hash: "736348617368", + RcvAddr: "726376", + SndAddr: "736e64", + OriginalTxHash: "747848617368", + Receivers: []string{}, + }, scrs[0]) +} + func TestNode_GetTransactionFromStorage(t *testing.T) { t.Parallel() @@ -459,6 +570,8 @@ func TestNode_GetTransactionWithResultsFromStorage(t *testing.T) { return &datafield.ResponseParseData{} }, }, + TxMarshaller: &marshallerMock.MarshalizerMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), } apiTransactionProc, _ := NewAPITransactionProcessor(args) @@ -1027,6 +1140,8 @@ func createAPITransactionProc(t *testing.T, epoch uint32, withDbLookupExt bool) TxTypeHandler: &testscommon.TxTypeHandlerMock{}, LogsFacade: &testscommon.LogsFacadeStub{}, DataFieldParser: dataFieldParser, + TxMarshaller: &marshallerMock.MarshalizerMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), } apiTransactionProc, err := NewAPITransactionProcessor(args) require.Nil(t, err) diff --git a/node/external/transactionAPI/apiTransactionResults.go b/node/external/transactionAPI/apiTransactionResults.go index 125376f39da..d4a89edfd15 100644 --- a/node/external/transactionAPI/apiTransactionResults.go +++ b/node/external/transactionAPI/apiTransactionResults.go @@ -102,10 +102,12 @@ func (arp *apiTransactionResultsProcessor) putSmartContractResultsInTransaction( scrHashesEpoch []*dblookupext.ScResultsHashesAndEpoch, ) error { for _, scrHashesE := range scrHashesEpoch { - err := arp.putSmartContractResultsInTransactionByHashesAndEpoch(tx, scrHashesE.ScResultsHashes, scrHashesE.Epoch) + scrsAPI, err := arp.getSmartContractResultsInTransactionByHashesAndEpoch(scrHashesE.ScResultsHashes, scrHashesE.Epoch) if err != nil { return err } + + tx.SmartContractResults = append(tx.SmartContractResults, scrsAPI...) } statusFilters := filters.NewStatusFilters(arp.shardCoordinator.SelfId()) @@ -113,21 +115,22 @@ func (arp *apiTransactionResultsProcessor) putSmartContractResultsInTransaction( return nil } -func (arp *apiTransactionResultsProcessor) putSmartContractResultsInTransactionByHashesAndEpoch(tx *transaction.ApiTransactionResult, scrsHashes [][]byte, epoch uint32) error { +func (arp *apiTransactionResultsProcessor) getSmartContractResultsInTransactionByHashesAndEpoch(scrsHashes [][]byte, epoch uint32) ([]*transaction.ApiSmartContractResult, error) { + scrsAPI := make([]*transaction.ApiSmartContractResult, 0, len(scrsHashes)) for _, scrHash := range scrsHashes { scr, err := arp.getScrFromStorage(scrHash, epoch) if err != nil { - return fmt.Errorf("%w: %v, hash = %s", errCannotLoadContractResults, err, hex.EncodeToString(scrHash)) + return nil, fmt.Errorf("%w: %v, hash = %s", errCannotLoadContractResults, err, hex.EncodeToString(scrHash)) } scrAPI := arp.adaptSmartContractResult(scrHash, scr) arp.loadLogsIntoContractResults(scrHash, epoch, scrAPI) - tx.SmartContractResults = append(tx.SmartContractResults, scrAPI) + scrsAPI = append(scrsAPI, scrAPI) } - return nil + return scrsAPI, nil } func (arp *apiTransactionResultsProcessor) loadLogsIntoTransaction(hash []byte, tx *transaction.ApiTransactionResult, epoch uint32) { diff --git a/node/external/transactionAPI/check.go b/node/external/transactionAPI/check.go index 0959ba6c5db..012aae77618 100644 --- a/node/external/transactionAPI/check.go +++ b/node/external/transactionAPI/check.go @@ -1,6 +1,8 @@ package transactionAPI import ( + "fmt" + "github.com/multiversx/mx-chain-core-go/core/check" "github.com/multiversx/mx-chain-go/process" ) @@ -42,6 +44,12 @@ func checkNilArgs(arg *ArgAPITransactionProcessor) error { if check.IfNilReflect(arg.DataFieldParser) { return ErrNilDataFieldParser } + if check.IfNil(arg.TxMarshaller) { + return fmt.Errorf("%w for tx marshaller", process.ErrNilMarshalizer) + } + if check.IfNil(arg.EnableEpochsHandler) { + return process.ErrNilEnableEpochsHandler + } return nil } diff --git a/node/external/transactionAPI/errors.go b/node/external/transactionAPI/errors.go index 924bd6040a5..105d6c3e930 100644 --- a/node/external/transactionAPI/errors.go +++ b/node/external/transactionAPI/errors.go @@ -31,3 +31,6 @@ var ErrCannotRetrieveTransactions = errors.New("transactions cannot be retrieved // ErrInvalidAddress signals that the address is invalid var ErrInvalidAddress = errors.New("invalid address") + +// ErrDBLookExtensionIsNotEnabled signals that the db look extension is not enabled +var ErrDBLookExtensionIsNotEnabled = errors.New("db look extension is not enabled") diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor.go b/node/external/transactionAPI/gasUsedAndFeeProcessor.go index f0036bc136b..c4cd9578394 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor.go @@ -4,19 +4,35 @@ 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" + "github.com/multiversx/mx-chain-go/process" datafield "github.com/multiversx/mx-chain-vm-common-go/parsers/dataField" ) type gasUsedAndFeeProcessor struct { - feeComputer feeComputer - pubKeyConverter core.PubkeyConverter + feeComputer feeComputer + pubKeyConverter core.PubkeyConverter + argsParser process.ArgumentsParser + marshaller marshal.Marshalizer + enableEpochsHandler common.EnableEpochsHandler } -func newGasUsedAndFeeProcessor(txFeeCalculator feeComputer, pubKeyConverter core.PubkeyConverter) *gasUsedAndFeeProcessor { +func newGasUsedAndFeeProcessor( + txFeeCalculator feeComputer, + pubKeyConverter core.PubkeyConverter, + argsParser process.ArgumentsParser, + marshaller marshal.Marshalizer, + enableEpochsHandler common.EnableEpochsHandler, +) *gasUsedAndFeeProcessor { return &gasUsedAndFeeProcessor{ - feeComputer: txFeeCalculator, - pubKeyConverter: pubKeyConverter, + feeComputer: txFeeCalculator, + pubKeyConverter: pubKeyConverter, + argsParser: argsParser, + marshaller: marshaller, + enableEpochsHandler: enableEpochsHandler, } } @@ -27,30 +43,109 @@ func (gfp *gasUsedAndFeeProcessor) computeAndAttachGasUsedAndFee(tx *transaction tx.GasUsed = gasUsed tx.Fee = fee.String() - if tx.IsRelayed || gfp.isESDTOperationWithSCCall(tx) { + isFeeFixActive := gfp.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, tx.Epoch) + isRelayedBeforeFix := tx.IsRelayed && !isFeeFixActive + if isRelayedBeforeFix || gfp.isESDTOperationWithSCCall(tx) { tx.GasUsed = tx.GasLimit tx.Fee = tx.InitiallyPaidFee } + userTx, initialTotalFee, isRelayed := gfp.getFeeOfRelayed(tx) + isRelayedAfterFix := isRelayed && isFeeFixActive + if isRelayedAfterFix { + tx.InitiallyPaidFee = initialTotalFee.String() + tx.Fee = initialTotalFee.String() + tx.GasUsed = big.NewInt(0).Div(initialTotalFee, big.NewInt(0).SetUint64(tx.GasPrice)).Uint64() + } + hasRefundForSender := false for _, scr := range tx.SmartContractResults { if !scr.IsRefund || scr.RcvAddr != tx.Sender { continue } - if scr.RcvAddr != tx.Sender { - 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) (*transaction.ApiTransactionResult, *big.Int, bool) { + if !tx.IsRelayed { + return nil, nil, false + } + + if len(tx.Data) == 0 { + return nil, nil, false + } + + funcName, args, err := gfp.argsParser.ParseCallData(string(tx.Data)) + if err != nil { + return nil, nil, false + } + + if funcName == core.RelayedTransaction { + return gfp.handleRelayedV1(args, tx) + } + + if funcName == core.RelayedTransactionV2 { + return gfp.handleRelayedV2(args, tx) + } + + return nil, nil, false +} + +func (gfp *gasUsedAndFeeProcessor) handleRelayedV1(args [][]byte, tx *transaction.ApiTransactionResult) (*transaction.ApiTransactionResult, *big.Int, bool) { + if len(args) != 1 { + return nil, nil, false + } + + innerTx := &transaction.Transaction{} + err := gfp.marshaller.Unmarshal(innerTx, args[0]) + if err != nil { + return nil, nil, false + } + + gasUsed := gfp.feeComputer.ComputeGasLimit(tx) + fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsed) + + innerTxApiResult := &transaction.ApiTransactionResult{ + Tx: innerTx, + Epoch: tx.Epoch, + } + innerFee := gfp.feeComputer.ComputeTransactionFee(innerTxApiResult) + + return innerTxApiResult, big.NewInt(0).Add(fee, innerFee), true +} + +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() + innerTx.Data = args[2] + innerTx.Signature = args[3] + innerTx.Value = big.NewInt(0) + innerTx.GasPrice = tx.GasPrice + innerTx.GasLimit = tx.GasLimit - gfp.feeComputer.ComputeGasLimit(tx) + innerTx.SndAddr = tx.Tx.GetRcvAddr() + + gasUsed := gfp.feeComputer.ComputeGasLimit(tx) + fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, gasUsed) + + innerTxApiResult := &transaction.ApiTransactionResult{ + Tx: innerTx, + Epoch: tx.Epoch, + } + innerFee := gfp.feeComputer.ComputeTransactionFee(innerTxApiResult) + + 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) { @@ -58,15 +153,13 @@ 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() + gfp.setGasUsedAndFeeBaseOnRefundValue(tx, userTx, big.NewInt(0)) } if core.SignalErrorOperation == event.Identifier { fee := gfp.feeComputer.ComputeTxFeeBasedOnGasUsed(tx, tx.GasLimit) @@ -75,9 +168,28 @@ 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() } diff --git a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go index 99541bfef5d..8c5c80826c0 100644 --- a/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go +++ b/node/external/transactionAPI/gasUsedAndFeeProcessor_test.go @@ -7,10 +7,12 @@ import ( "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/core/pubkeyConverter" "github.com/multiversx/mx-chain-core-go/data/transaction" + "github.com/multiversx/mx-chain-core-go/marshal" "github.com/multiversx/mx-chain-go/common" "github.com/multiversx/mx-chain-go/node/external/timemachine/fee" "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/process/economics" + "github.com/multiversx/mx-chain-go/process/smartContract" "github.com/multiversx/mx-chain-go/testscommon" "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/epochNotifier" @@ -38,7 +40,13 @@ func TestComputeTransactionGasUsedAndFeeMoveBalance(t *testing.T) { feeComp, _ := fee.NewFeeComputer(createEconomicsData(&enableEpochsHandlerMock.EnableEpochsHandlerStub{})) computer := fee.NewTestFeeComputer(feeComp) - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(computer, pubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + &testscommon.ArgumentParserMock{}, + &testscommon.MarshallerStub{}, + enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + ) sender := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" receiver := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" @@ -68,7 +76,13 @@ func TestComputeTransactionGasUsedAndFeeLogWithError(t *testing.T) { })) computer := fee.NewTestFeeComputer(feeComp) - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(computer, pubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + &testscommon.ArgumentParserMock{}, + &testscommon.MarshallerStub{}, + enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + ) sender := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" receiver := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" @@ -111,7 +125,13 @@ func TestComputeTransactionGasUsedAndFeeRelayedTxWithWriteLog(t *testing.T) { })) computer := fee.NewTestFeeComputer(feeComp) - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(computer, pubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + &testscommon.ArgumentParserMock{}, + &testscommon.MarshallerStub{}, + enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + ) sender := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" receiver := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" @@ -149,7 +169,13 @@ func TestComputeTransactionGasUsedAndFeeTransactionWithScrWithRefund(t *testing. })) computer := fee.NewTestFeeComputer(feeComp) - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(computer, pubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + &testscommon.ArgumentParserMock{}, + &testscommon.MarshallerStub{}, + enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + ) sender := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" receiver := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" @@ -197,7 +223,13 @@ func TestNFTTransferWithScCall(t *testing.T) { computer := fee.NewTestFeeComputer(feeComp) req.Nil(err) - gasUsedAndFeeProc := newGasUsedAndFeeProcessor(computer, pubKeyConverter) + gasUsedAndFeeProc := newGasUsedAndFeeProcessor( + computer, + pubKeyConverter, + &testscommon.ArgumentParserMock{}, + &testscommon.MarshallerStub{}, + enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), + ) sender := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" receiver := "erd1wc3uh22g2aved3qeehkz9kzgrjwxhg9mkkxp2ee7jj7ph34p2csq0n2y5x" @@ -221,3 +253,144 @@ func TestNFTTransferWithScCall(t *testing.T) { req.Equal(uint64(55_000_000), tx.GasUsed) req.Equal("822250000000000", tx.Fee) } + +func TestComputeAndAttachGasUsedAndFeeTransactionWithMultipleScrWithRefund(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/scInvokingWithMultipleRefunds.json") + require.NoError(t, err) + + txWithSRefundSCR.Fee = "" + txWithSRefundSCR.GasUsed = 0 + + 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, + } + + gasUsedAndFeeProc.computeAndAttachGasUsedAndFee(txWithSRefundSCR) + require.Equal(t, uint64(20313408), txWithSRefundSCR.GasUsed) + require.Equal(t, "319459080000000", txWithSRefundSCR.Fee) +} + +func TestComputeAndAttachGasUsedAndFeeFailedRelayedV1(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/failedRelayedV1.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(6148000), txWithSRefundSCR.GasUsed) + 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/failedRelayedV1.json b/node/external/transactionAPI/testData/failedRelayedV1.json new file mode 100644 index 00000000000..e2b1be88bee --- /dev/null +++ b/node/external/transactionAPI/testData/failedRelayedV1.json @@ -0,0 +1,60 @@ +{ + "type": "normal", + "processingTypeOnSource": "RelayedTx", + "processingTypeOnDestination": "RelayedTx", + "hash": "efe3e8fa273fc2db4d559185e9729f7bbf17f617e28424b6a6533fb193caf561", + "nonce": 125, + "value": "0", + "receiver": "erd1x9hax7mdqux0nak9ahxrc2g75h5ckpfs4ssr8l7tkxscaa293x6q8ffd4e", + "sender": "erd1tn62hjp72rznp8vq0lplva5csav6rccpqqdungpxtqz0g2hcq6uq9k4cc6", + "gasPrice": 1000000000, + "gasLimit": 6148000, + "data": "cmVsYXllZFR4QDdiMjI2ZTZmNmU2MzY1MjIzYTM0MzcyYzIyNzM2NTZlNjQ2NTcyMjIzYTIyNGQ1NzJmNTQ2NTMyMzA0ODQ0NTA2ZTMyNzg2NTMzNGQ1MDQzNmI2NTcwNjU2ZDRjNDI1NDQzNzM0OTQ0NTAyZjc5Mzc0NzY4NmE3NjU2NDY2OTYyNTEzZDIyMmMyMjcyNjU2MzY1Njk3NjY1NzIyMjNhMjI0MTQxNDE0MTQxNDE0MTQxNDE0MTQxNDY0MTQ0MzU1MzM3NTg2MjUwNzk1NTQzNzU3NzRiNDk1MTM0NmUzNzMxNTE3OTZmNGE1ODM1NzM1NDQyNzI2NzNkMjIyYzIyNzY2MTZjNzU2NTIyM2EzMTMwMzAzMDMwMzAzMDMwMzAzMDMwMzAzMDMwMzAzMDMwMzAzMDJjMjI2NzYxNzM1MDcyNjk2MzY1MjIzYTMxMzAzMDMwMzAzMDMwMzAzMDMwMmMyMjY3NjE3MzRjNjk2ZDY5NzQyMjNhMzUzMDMwMzAzMDMwMzAyYzIyNjQ2MTc0NjEyMjNhMjI1OTU3NTI2YjUxNDQ0MTc4NTE0NDQxNzk1MTQ0NDE3YTUxNDQ0MTMwNTE0NDQxMzEyMjJjMjI3MzY5Njc2ZTYxNzQ3NTcyNjUyMjNhMjI3NjRjNjQ2ZDMyMmY0ZTQ0NTQ0NDc3MzgzMTMxNTEzMDYyNzgyYjU4NGI1MTc4NTA0NTJmNzY0OTU3NDM2ODRlNzI2OTU1NmE3ODcyNzAyZjU5Mzg1MDRlNzI0ZDQ1NmM2NTQ3NmUzNTMxNTM3NjUyNTk2NDQ3MzQ2ZjQ3NTc3MjQ5Njk0MzQ4Mzk2YTMxNzY0ZjRiNmY1OTJmNDg1NTUyNjE0ZTQxNDg0MjUxM2QzZDIyMmMyMjYzNjg2MTY5NmU0OTQ0MjIzYTIyNTY0MTNkM2QyMjJjMjI3NjY1NzI3MzY5NmY2ZTIyM2EzMjdk", + "sourceShard": 0, + "destinationShard": 0, + "logs": { + "address": "erd1qqqqqqqqqqqqqpgq8efw6ak0e9q2as9zzr38aa2r9gy4lxcnq6uqpefzvu", + "events": [ + { + "address": "erd1qqqqqqqqqqqqqpgq8efw6ak0e9q2as9zzr38aa2r9gy4lxcnq6uqpefzvu", + "identifier": "signalError", + "topics": [ + "MW/Te20HDPn2xe3MPCkepemLBTCsIDP/y7GhjvVFibQ=", + "ZnVuY3Rpb24gZG9lcyBub3QgYWNjZXB0IEVHTEQgcGF5bWVudA==" + ], + "data": "QDY1Nzg2NTYzNzU3NDY5NmY2ZTIwNjY2MTY5NmM2NTY0", + "additionalData": [ + "QDY1Nzg2NTYzNzU3NDY5NmY2ZTIwNjY2MTY5NmM2NTY0" + ] + }, + { + "address": "erd1qqqqqqqqqqqqqpgq8efw6ak0e9q2as9zzr38aa2r9gy4lxcnq6uqpefzvu", + "identifier": "signalError", + "topics": [ + "XPSryD5QxTCdgH/D9naYh1mh4wEAG8mgJlgE9Cr4Brg=", + "ZnVuY3Rpb24gZG9lcyBub3QgYWNjZXB0IEVHTEQgcGF5bWVudA==" + ], + "data": null, + "additionalData": [ + "" + ] + }, + { + "address": "erd1x9hax7mdqux0nak9ahxrc2g75h5ckpfs4ssr8l7tkxscaa293x6q8ffd4e", + "identifier": "internalVMErrors", + "topics": [ + "AAAAAAAAAAAFAD5S7XbPyUCuwKIQ4n71QyoJX5sTBrg=", + "YWRk" + ], + "data": "CglydW50aW1lLmdvOjg1NiBbZXhlY3V0aW9uIGZhaWxlZF0gW2FkZF0KCXJ1bnRpbWUuZ286ODU2IFtleGVjdXRpb24gZmFpbGVkXSBbYWRkXQoJcnVudGltZS5nbzo4NTMgW2Z1bmN0aW9uIGRvZXMgbm90IGFjY2VwdCBFR0xEIHBheW1lbnRd", + "additionalData": [ + "CglydW50aW1lLmdvOjg1NiBbZXhlY3V0aW9uIGZhaWxlZF0gW2FkZF0KCXJ1bnRpbWUuZ286ODU2IFtleGVjdXRpb24gZmFpbGVkXSBbYWRkXQoJcnVudGltZS5nbzo4NTMgW2Z1bmN0aW9uIGRvZXMgbm90IGFjY2VwdCBFR0xEIHBheW1lbnRd" + ] + } + ] + }, + "status": "success", + "operation": "transfer", + "function": "add", + "isRelayed": true +} 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/node/external/transactionAPI/testData/scInvokingWithMultipleRefunds.json b/node/external/transactionAPI/testData/scInvokingWithMultipleRefunds.json new file mode 100644 index 00000000000..6223da3db9f --- /dev/null +++ b/node/external/transactionAPI/testData/scInvokingWithMultipleRefunds.json @@ -0,0 +1,115 @@ +{ + "type": "normal", + "processingTypeOnSource": "SCInvoking", + "processingTypeOnDestination": "SCInvoking", + "hash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "nonce": 5720, + "value": "88000000000000000", + "receiver": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "sender": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "gasPrice": 1000000000, + "gasLimit": 45000000, + "gasUsed": 20313408, + "data": "YnV5QDEzMDA5N0A1NjQzNGY0OTRlMmQzMjY0MzQzNDMzNjRAMDFAMDE4NmEw", + "smartContractResults": [ + { + "hash": "ebc994f2e46037fbf16f3426ab3ea40a43b648620209372bcb158153053fb5f9", + "nonce": 5721, + "value": 246865920000000, + "receiver": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "sender": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "data": "@6f6b", + "prevTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 0, + "gasPrice": 1000000000, + "operation": "transfer", + "isRefund": true + }, + { + "hash": "402b39eba60202424565e224ab7121fd49eb8da366bc8b7b5d38496f1ce29f0d", + "nonce": 0, + "value": 2640000000000000, + "receiver": "erd1qqqqqqqqqqqqqpgq8538ku69p97lq4eug75y8d6g6yfwhd7c45qs4zvejt", + "sender": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "data": "depositRoyalties@0000000000000000050073175b6392a2f2661f2fb1fd2552787534433af98638", + "prevTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 5500000, + "gasPrice": 1000000000, + "originalSender": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "operation": "transfer", + "function": "depositRoyalties" + }, + { + "hash": "9912a1b3d3918a79f9c560ff2d81b24b316a89cbefd195325807132319147502", + "nonce": 0, + "value": 84480000000000000, + "receiver": "erd1qtkml3n4lwy5hxdmdfe67nm5jg5v6kqrtsdjt76za35ms4nnvghsjfujaw", + "sender": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "prevTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 0, + "gasPrice": 1000000000, + "originalSender": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "operation": "transfer" + }, + { + "hash": "11c18202b3d117fa3301e8cbc72f6d258d56b70686fa174bffa331079b753b31", + "nonce": 0, + "value": 0, + "receiver": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "sender": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "data": "ESDTNFTTransfer@56434f494e2d326434343364@01@0186a0@08011204000186a022ef020801120d56696c6c6167657220436f696e1a200000000000000000050073175b6392a2f2661f2fb1fd2552787534433af9863820ac022a203e0e25256b5c0a5d5825deb7519eeae0468c2597533db2de10bb560ae317b7f0325068747470733a2f2f697066732e696f2f697066732f6261666b7265696864703577797975706a6174356a6d68726e706c786d3333616570737a67667333656733716c336e776f6268736d72376e747434325068747470733a2f2f697066732e696f2f697066732f6261666b726569636d727763366b6b7472646d6669797a66616f687664357977796f34746f343670776c6b3767363562366d6b74376835697a6f793a71746167733a6769616e74732c6769616e74732076696c6c6167652c6e70632c76696c6c6167657220636f696e3b6d657461646174613a6261666b726569636d727763366b6b7472646d6669797a66616f687664357977796f34746f343670776c6b3767363562366d6b74376835697a6f79", + "prevTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 0, + "gasPrice": 1000000000, + "originalSender": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "operation": "ESDTNFTTransfer" + }, + { + "hash": "3a814d0abb4c00c44bc8ba29007c51edc487daa17c7666efc9fad1f5a86d03a2", + "nonce": 1, + "value": 880000000000000, + "receiver": "erd1qqqqqqqqqqqqqpgq8538ku69p97lq4eug75y8d6g6yfwhd7c45qs4zvejt", + "sender": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "data": "deposit", + "prevTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 3500000, + "gasPrice": 1000000000, + "originalSender": "erd1trqrpnl7e5nsagfqh4qp2tfpqg7hjacsesrstuhjk76rgagag9ws87gy6l", + "operation": "transfer", + "function": "deposit" + }, + { + "hash": "b7a2e5cf1ddad2630ccf8c703c9494b9b446e3a25ce362f6ec7c739448e41cbf", + "nonce": 1, + "value": 26131840000000, + "receiver": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "sender": "erd1qqqqqqqqqqqqqpgq8538ku69p97lq4eug75y8d6g6yfwhd7c45qs4zvejt", + "data": "@6f6b", + "prevTxHash": "402b39eba60202424565e224ab7121fd49eb8da366bc8b7b5d38496f1ce29f0d", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 0, + "gasPrice": 1000000000, + "operation": "transfer", + "isRefund": true + }, + { + "hash": "40d329ecd05ffa543a41efd216c463f2ec229432d7b5c1c9132af29e406f389d", + "nonce": 2, + "value": 7494280000000, + "receiver": "erd1qqqqqqqqqqqqqpgq6wegs2xkypfpync8mn2sa5cmpqjlvrhwz5nqgepyg8", + "sender": "erd1qqqqqqqqqqqqqpgq8538ku69p97lq4eug75y8d6g6yfwhd7c45qs4zvejt", + "data": "@6f6b", + "prevTxHash": "3a814d0abb4c00c44bc8ba29007c51edc487daa17c7666efc9fad1f5a86d03a2", + "originalTxHash": "293256314626408acc866793cb4e762ec4b2925dbce3bfb166e39e4deea66e93", + "gasLimit": 0, + "gasPrice": 1000000000, + "operation": "transfer", + "isRefund": true + } + ] +} 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 c380c08b95d..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)) @@ -202,6 +201,7 @@ func InitConfigMetrics( appStatusHandler.SetUInt64Value(common.MetricEGLDInMultiTransferEnableEpoch, uint64(enableEpochs.EGLDInMultiTransferEnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricCryptoOpcodesV2EnableEpoch, uint64(enableEpochs.CryptoOpcodesV2EnableEpoch)) appStatusHandler.SetUInt64Value(common.MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch, uint64(enableEpochs.MultiESDTNFTTransferAndExecuteByUserEnableEpoch)) + appStatusHandler.SetUInt64Value(common.MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch, uint64(enableEpochs.FixRelayedMoveBalanceToNonPayableSCEnableEpoch)) for i, nodesChangeConfig := range enableEpochs.MaxNodesChangeEnableEpoch { epochEnable := fmt.Sprintf("%s%d%s", common.MetricMaxNodesChangeEnableEpoch, i, common.EpochEnableSuffix) diff --git a/node/metrics/metrics_test.go b/node/metrics/metrics_test.go index 395d42afc15..1aa3bd7be2e 100644 --- a/node/metrics/metrics_test.go +++ b/node/metrics/metrics_test.go @@ -208,9 +208,9 @@ func TestInitConfigMetrics(t *testing.T) { EGLDInMultiTransferEnableEpoch: 101, CryptoOpcodesV2EnableEpoch: 102, ScToScLogEventEnableEpoch: 103, - RelayedTransactionsV3EnableEpoch: 104, - FixRelayedBaseCostEnableEpoch: 105, - MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 106, + FixRelayedBaseCostEnableEpoch: 104, + MultiESDTNFTTransferAndExecuteByUserEnableEpoch: 105, + FixRelayedMoveBalanceToNonPayableSCEnableEpoch: 106, MaxNodesChangeEnableEpoch: []config.MaxNodesChangeConfig{ { EpochEnable: 0, @@ -329,9 +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_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/mock/apiTransactionHandlerStub.go b/node/mock/apiTransactionHandlerStub.go index 2ae18622197..4bd9ca4633f 100644 --- a/node/mock/apiTransactionHandlerStub.go +++ b/node/mock/apiTransactionHandlerStub.go @@ -15,6 +15,16 @@ type TransactionAPIHandlerStub struct { UnmarshalTransactionCalled func(txBytes []byte, txType transaction.TxType) (*transaction.ApiTransactionResult, error) UnmarshalReceiptCalled func(receiptBytes []byte) (*transaction.ApiReceipt, error) PopulateComputedFieldsCalled func(tx *transaction.ApiTransactionResult) + GetSCRsByTxHashCalled func(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) +} + +// GetSCRsByTxHash -- +func (tas *TransactionAPIHandlerStub) GetSCRsByTxHash(txHash string, scrHash string) ([]*transaction.ApiSmartContractResult, error) { + if tas.GetSCRsByTxHashCalled != nil { + return tas.GetSCRsByTxHashCalled(txHash, scrHash) + } + + return nil, nil } // GetTransaction - 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/factory/hostDriverFactory_test.go b/outport/factory/hostDriverFactory_test.go index d41079c0f55..d005ea4ba74 100644 --- a/outport/factory/hostDriverFactory_test.go +++ b/outport/factory/hostDriverFactory_test.go @@ -15,7 +15,7 @@ func TestCreateHostDriver(t *testing.T) { args := ArgsHostDriverFactory{ HostConfig: config.HostDriversConfig{ - URL: "localhost", + URL: "ws://localhost", RetryDurationInSec: 1, MarshallerType: "json", Mode: data.ModeClient, diff --git a/outport/factory/outportFactory_test.go b/outport/factory/outportFactory_test.go index 93b4657427b..94d8c38839c 100644 --- a/outport/factory/outportFactory_test.go +++ b/outport/factory/outportFactory_test.go @@ -122,7 +122,7 @@ func TestCreateOutport_SubscribeMultipleHostDrivers(t *testing.T) { Marshaller: &testscommon.MarshalizerMock{}, HostConfig: config.HostDriversConfig{ Enabled: true, - URL: "localhost", + URL: "ws://localhost", RetryDurationInSec: 1, MarshallerType: "json", Mode: data.ModeClient, @@ -132,7 +132,7 @@ func TestCreateOutport_SubscribeMultipleHostDrivers(t *testing.T) { Marshaller: &testscommon.MarshalizerMock{}, HostConfig: config.HostDriversConfig{ Enabled: false, - URL: "localhost", + URL: "ws://localhost", RetryDurationInSec: 1, MarshallerType: "json", Mode: data.ModeClient, @@ -142,7 +142,7 @@ func TestCreateOutport_SubscribeMultipleHostDrivers(t *testing.T) { Marshaller: &testscommon.MarshalizerMock{}, HostConfig: config.HostDriversConfig{ Enabled: true, - URL: "localhost", + URL: "ws://localhost", RetryDurationInSec: 1, MarshallerType: "json", Mode: data.ModeClient, diff --git a/outport/process/factory/outportDataProviderFactory.go b/outport/process/factory/outportDataProviderFactory.go index 68546df1c50..5bb2c698136 100644 --- a/outport/process/factory/outportDataProviderFactory.go +++ b/outport/process/factory/outportDataProviderFactory.go @@ -11,6 +11,7 @@ import ( "github.com/multiversx/mx-chain-go/outport/process/disabled" "github.com/multiversx/mx-chain-go/outport/process/transactionsfee" processTxs "github.com/multiversx/mx-chain-go/process" + "github.com/multiversx/mx-chain-go/process/smartContract" "github.com/multiversx/mx-chain-go/sharding" "github.com/multiversx/mx-chain-go/sharding/nodesCoordinator" "github.com/multiversx/mx-chain-go/state" @@ -60,11 +61,13 @@ func CreateOutportDataProvider(arg ArgOutportDataProviderFactory) (outport.DataP } transactionsFeeProc, err := transactionsfee.NewTransactionsFeeProcessor(transactionsfee.ArgTransactionsFeeProcessor{ - Marshaller: arg.Marshaller, - TransactionsStorer: arg.TransactionsStorer, - ShardCoordinator: arg.ShardCoordinator, - TxFeeCalculator: arg.EconomicsData, - PubKeyConverter: arg.AddressConverter, + Marshaller: arg.Marshaller, + TransactionsStorer: arg.TransactionsStorer, + ShardCoordinator: arg.ShardCoordinator, + TxFeeCalculator: arg.EconomicsData, + PubKeyConverter: arg.AddressConverter, + ArgsParser: smartContract.NewArgumentParser(), + EnableEpochsHandler: arg.EnableEpochsHandler, }) if err != nil { return nil, err diff --git a/outport/process/interface.go b/outport/process/interface.go index 5fcb19020f3..bec97f362b3 100644 --- a/outport/process/interface.go +++ b/outport/process/interface.go @@ -17,7 +17,7 @@ type AlteredAccountsProviderHandler interface { // TransactionsFeeHandler defines the functionality needed for computation of the transaction fee and gas used type TransactionsFeeHandler interface { - PutFeeAndGasUsed(pool *outport.TransactionPool) error + PutFeeAndGasUsed(pool *outport.TransactionPool, epoch uint32) error IsInterfaceNil() bool } diff --git a/outport/process/outportDataProvider.go b/outport/process/outportDataProvider.go index a99e0bc4827..aec1f15df8b 100644 --- a/outport/process/outportDataProvider.go +++ b/outport/process/outportDataProvider.go @@ -100,7 +100,7 @@ func (odp *outportDataProvider) PrepareOutportSaveBlockData(arg ArgPrepareOutpor return nil, err } - err = odp.transactionsFeeProcessor.PutFeeAndGasUsed(pool) + err = odp.transactionsFeeProcessor.PutFeeAndGasUsed(pool, arg.Header.GetEpoch()) if err != nil { return nil, fmt.Errorf("transactionsFeeProcessor.PutFeeAndGasUsed %w", err) } diff --git a/outport/process/outportDataProvider_test.go b/outport/process/outportDataProvider_test.go index c240fe50ab7..ef1422d230a 100644 --- a/outport/process/outportDataProvider_test.go +++ b/outport/process/outportDataProvider_test.go @@ -16,6 +16,7 @@ import ( "github.com/multiversx/mx-chain-go/outport/process/transactionsfee" "github.com/multiversx/mx-chain-go/testscommon" commonMocks "github.com/multiversx/mx-chain-go/testscommon/common" + "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/genericMocks" "github.com/multiversx/mx-chain-go/testscommon/hashingMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" @@ -25,10 +26,12 @@ import ( func createArgOutportDataProvider() ArgOutportDataProvider { txsFeeProc, _ := transactionsfee.NewTransactionsFeeProcessor(transactionsfee.ArgTransactionsFeeProcessor{ - Marshaller: &marshallerMock.MarshalizerMock{}, - TransactionsStorer: &genericMocks.StorerMock{}, - ShardCoordinator: &testscommon.ShardsCoordinatorMock{}, - TxFeeCalculator: &mock.EconomicsHandlerMock{}, + Marshaller: &marshallerMock.MarshalizerMock{}, + TransactionsStorer: &genericMocks.StorerMock{}, + ShardCoordinator: &testscommon.ShardsCoordinatorMock{}, + TxFeeCalculator: &mock.EconomicsHandlerMock{}, + ArgsParser: &testscommon.ArgumentParserMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), }) return ArgOutportDataProvider{ diff --git a/outport/process/transactionsfee/transactionsFeeProcessor.go b/outport/process/transactionsfee/transactionsFeeProcessor.go index 6520db7635d..30bcf0fca76 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor.go @@ -6,9 +6,13 @@ 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" "github.com/multiversx/mx-chain-core-go/marshal" + "github.com/multiversx/mx-chain-go/common" + "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/sharding" "github.com/multiversx/mx-chain-go/storage" logger "github.com/multiversx/mx-chain-logger-go" @@ -19,19 +23,24 @@ const loggerName = "outport/process/transactionsfee" // ArgTransactionsFeeProcessor holds the arguments needed for creating a new instance of transactionsFeeProcessor type ArgTransactionsFeeProcessor struct { - Marshaller marshal.Marshalizer - TransactionsStorer storage.Storer - ShardCoordinator sharding.Coordinator - TxFeeCalculator FeesProcessorHandler - PubKeyConverter core.PubkeyConverter + Marshaller marshal.Marshalizer + TransactionsStorer storage.Storer + ShardCoordinator sharding.Coordinator + TxFeeCalculator FeesProcessorHandler + PubKeyConverter core.PubkeyConverter + ArgsParser process.ArgumentsParser + EnableEpochsHandler common.EnableEpochsHandler } type transactionsFeeProcessor struct { - txGetter transactionGetter - txFeeCalculator FeesProcessorHandler - shardCoordinator sharding.Coordinator - dataFieldParser dataFieldParser - log logger.Logger + txGetter transactionGetter + txFeeCalculator FeesProcessorHandler + shardCoordinator sharding.Coordinator + dataFieldParser dataFieldParser + log logger.Logger + marshaller marshal.Marshalizer + argsParser process.ArgumentsParser + enableEpochsHandler common.EnableEpochsHandler } // NewTransactionsFeeProcessor will create a new instance of transactionsFeeProcessor @@ -50,11 +59,14 @@ func NewTransactionsFeeProcessor(arg ArgTransactionsFeeProcessor) (*transactions } return &transactionsFeeProcessor{ - txFeeCalculator: arg.TxFeeCalculator, - shardCoordinator: arg.ShardCoordinator, - txGetter: newTxGetter(arg.TransactionsStorer, arg.Marshaller), - log: logger.GetOrCreate(loggerName), - dataFieldParser: parser, + txFeeCalculator: arg.TxFeeCalculator, + shardCoordinator: arg.ShardCoordinator, + txGetter: newTxGetter(arg.TransactionsStorer, arg.Marshaller), + log: logger.GetOrCreate(loggerName), + dataFieldParser: parser, + marshaller: arg.Marshaller, + argsParser: arg.ArgsParser, + enableEpochsHandler: arg.EnableEpochsHandler, }, nil } @@ -74,16 +86,22 @@ func checkArg(arg ArgTransactionsFeeProcessor) error { if check.IfNil(arg.PubKeyConverter) { return core.ErrNilPubkeyConverter } + if check.IfNil(arg.ArgsParser) { + return process.ErrNilArgumentParser + } + if check.IfNil(arg.EnableEpochsHandler) { + return process.ErrNilEnableEpochsHandler + } return nil } // PutFeeAndGasUsed will compute and set in transactions pool fee and gas used -func (tep *transactionsFeeProcessor) PutFeeAndGasUsed(pool *outportcore.TransactionPool) error { +func (tep *transactionsFeeProcessor) PutFeeAndGasUsed(pool *outportcore.TransactionPool, epoch uint32) error { tep.prepareInvalidTxs(pool) txsWithResultsMap := prepareTransactionsAndScrs(pool) - tep.prepareNormalTxs(txsWithResultsMap) + tep.prepareNormalTxs(txsWithResultsMap, epoch) return tep.prepareScrsNoTx(txsWithResultsMap) } @@ -97,7 +115,7 @@ func (tep *transactionsFeeProcessor) prepareInvalidTxs(pool *outportcore.Transac } } -func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *transactionsAndScrsHolder) { +func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *transactionsAndScrsHolder, epoch uint32) { for txHashHex, txWithResult := range transactionsAndScrs.txsWithResults { txHandler := txWithResult.GetTxHandler() @@ -110,21 +128,33 @@ func (tep *transactionsFeeProcessor) prepareNormalTxs(transactionsAndScrs *trans feeInfo.SetFee(fee) feeInfo.SetInitialPaidFee(initialPaidFee) - if isRelayedTx(txWithResult) || tep.isESDTOperationWithSCCall(txHandler) { + isRelayed := isRelayedTx(txWithResult) + isFeeFixActive := tep.enableEpochsHandler.IsFlagEnabledInEpoch(common.FixRelayedBaseCostFlag, epoch) + isRelayedBeforeFix := isRelayed && !isFeeFixActive + if isRelayedBeforeFix || tep.isESDTOperationWithSCCall(txHandler) { feeInfo.SetGasUsed(txWithResult.GetTxHandler().GetGasLimit()) feeInfo.SetFee(initialPaidFee) } - if len(txHandler.GetUserTransactions()) > 0 { - tep.prepareRelayedTxV3WithResults(txHashHex, txWithResult) - continue + userTx, totalFee, isRelayed := tep.getFeeOfRelayed(txWithResult) + isRelayedAfterFix := isRelayed && isFeeFixActive + if isRelayedAfterFix { + feeInfo.SetFee(totalFee) + feeInfo.SetInitialPaidFee(totalFee) + feeInfo.SetGasUsed(big.NewInt(0).Div(totalFee, big.NewInt(0).SetUint64(txHandler.GetGasPrice())).Uint64()) + } - tep.prepareTxWithResults(txHashHex, txWithResult) + tep.prepareTxWithResults(txHashHex, txWithResult, userTx, epoch) } } -func (tep *transactionsFeeProcessor) prepareTxWithResults(txHashHex string, txWithResults *transactionWithResults) { +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) @@ -133,48 +163,83 @@ 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) + tep.setGasUsedAndFeeBasedOnRefundValue(txWithResults, userTx, scr.Value, epoch) hasRefund = true break } } - tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefund) - + tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, userTx, hasRefund, epoch) } -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 - } +func (tep *transactionsFeeProcessor) getFeeOfRelayed(tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { + if len(tx.GetTxHandler().GetData()) == 0 { + return nil, nil, false + } - if !isRefundForRelayed(scr, txWithResults.GetTxHandler()) { - continue - } + funcName, args, err := tep.argsParser.ParseCallData(string(tx.GetTxHandler().GetData())) + if err != nil { + return nil, nil, false + } - refundsValue.Add(refundsValue, scr.Value) + if funcName == core.RelayedTransaction { + return tep.handleRelayedV1(args, tx) } - gasUsed, fee := tep.txFeeCalculator.ComputeGasUsedAndFeeBasedOnRefundValue(txWithResults.GetTxHandler(), refundsValue) + if funcName == core.RelayedTransactionV2 { + return tep.handleRelayedV2(args, tx) + } - txWithResults.GetFeeInfo().SetGasUsed(gasUsed) - txWithResults.GetFeeInfo().SetFee(fee) + return nil, nil, false +} - hasRefunds := refundsValue.Cmp(big.NewInt(0)) == 1 - tep.prepareTxWithResultsBasedOnLogs(txHashHex, txWithResults, hasRefunds) +func (tep *transactionsFeeProcessor) handleRelayedV1(args [][]byte, tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { + if len(args) != 1 { + return nil, nil, false + } + innerTx := &transaction.Transaction{} + err := tep.marshaller.Unmarshal(innerTx, args[0]) + if err != nil { + return nil, nil, false + } + + txHandler := tx.GetTxHandler() + gasUsed := tep.txFeeCalculator.ComputeGasLimit(txHandler) + fee := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(txHandler, gasUsed) + + innerFee := tep.txFeeCalculator.ComputeTxFee(innerTx) + + return innerTx, big.NewInt(0).Add(fee, innerFee), true +} + +func (tep *transactionsFeeProcessor) handleRelayedV2(args [][]byte, tx *transactionWithResults) (data.TransactionHandler, *big.Int, bool) { + txHandler := tx.GetTxHandler() + + innerTx := &transaction.Transaction{} + innerTx.RcvAddr = args[0] + innerTx.Nonce = big.NewInt(0).SetBytes(args[1]).Uint64() + innerTx.Data = args[2] + innerTx.Signature = args[3] + innerTx.Value = big.NewInt(0) + innerTx.GasPrice = txHandler.GetGasPrice() + innerTx.GasLimit = txHandler.GetGasLimit() - tep.txFeeCalculator.ComputeGasLimit(txHandler) + innerTx.SndAddr = txHandler.GetRcvAddr() + + gasUsed := tep.txFeeCalculator.ComputeGasLimit(txHandler) + fee := tep.txFeeCalculator.ComputeTxFeeBasedOnGasUsed(txHandler, gasUsed) + + innerFee := tep.txFeeCalculator.ComputeTxFee(innerTx) + + return innerTx, big.NewInt(0).Add(fee, innerFee), true } func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( txHashHex string, txWithResults *transactionWithResults, + userTx data.TransactionHandler, hasRefund bool, + epoch uint32, ) { tx := txWithResults.GetTxHandler() if check.IfNil(tx) { @@ -189,10 +254,7 @@ func (tep *transactionsFeeProcessor) prepareTxWithResultsBasedOnLogs( for _, event := range txWithResults.log.GetLogEvents() { if core.WriteLogIdentifier == string(event.GetIdentifier()) && !hasRefund { - 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()) { @@ -201,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 { @@ -231,10 +316,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) + } 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 + } - scrHandler.GetFeeInfo().SetGasUsed(gasUsed) - scrHandler.GetFeeInfo().SetFee(fee) + 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 diff --git a/outport/process/transactionsfee/transactionsFeeProcessor_test.go b/outport/process/transactionsfee/transactionsFeeProcessor_test.go index 8ff4cf14501..6f0e0f94c35 100644 --- a/outport/process/transactionsfee/transactionsFeeProcessor_test.go +++ b/outport/process/transactionsfee/transactionsFeeProcessor_test.go @@ -11,7 +11,9 @@ import ( "github.com/multiversx/mx-chain-core-go/data/smartContractResult" "github.com/multiversx/mx-chain-core-go/data/transaction" "github.com/multiversx/mx-chain-go/outport/mock" + "github.com/multiversx/mx-chain-go/process" "github.com/multiversx/mx-chain-go/testscommon" + "github.com/multiversx/mx-chain-go/testscommon/enableEpochsHandlerMock" "github.com/multiversx/mx-chain-go/testscommon/genericMocks" "github.com/multiversx/mx-chain-go/testscommon/marshallerMock" logger "github.com/multiversx/mx-chain-logger-go" @@ -22,11 +24,13 @@ var pubKeyConverter, _ = pubkeyConverter.NewBech32PubkeyConverter(32, "erd") func prepareMockArg() ArgTransactionsFeeProcessor { return ArgTransactionsFeeProcessor{ - Marshaller: marshallerMock.MarshalizerMock{}, - TransactionsStorer: genericMocks.NewStorerMock(), - ShardCoordinator: &testscommon.ShardsCoordinatorMock{}, - TxFeeCalculator: &mock.EconomicsHandlerMock{}, - PubKeyConverter: pubKeyConverter, + Marshaller: marshallerMock.MarshalizerMock{}, + TransactionsStorer: genericMocks.NewStorerMock(), + ShardCoordinator: &testscommon.ShardsCoordinatorMock{}, + TxFeeCalculator: &mock.EconomicsHandlerMock{}, + PubKeyConverter: pubKeyConverter, + ArgsParser: &testscommon.ArgumentParserMock{}, + EnableEpochsHandler: enableEpochsHandlerMock.NewEnableEpochsHandlerStub(), } } @@ -53,6 +57,16 @@ func TestNewTransactionFeeProcessor(t *testing.T) { _, err = NewTransactionsFeeProcessor(arg) require.Equal(t, ErrNilTransactionFeeCalculator, err) + arg = prepareMockArg() + arg.ArgsParser = nil + _, err = NewTransactionsFeeProcessor(arg) + require.Equal(t, process.ErrNilArgumentParser, err) + + arg = prepareMockArg() + arg.EnableEpochsHandler = nil + _, err = NewTransactionsFeeProcessor(arg) + require.Equal(t, process.ErrNilEnableEpochsHandler, err) + arg = prepareMockArg() txsFeeProc, err := NewTransactionsFeeProcessor(arg) require.NotNil(t, txsFeeProc) @@ -125,7 +139,7 @@ func TestPutFeeAndGasUsedTx1(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(1673728170000000), initialTx.GetFeeInfo().GetFee()) require.Equal(t, uint64(7982817), initialTx.GetFeeInfo().GetGasUsed()) @@ -175,7 +189,7 @@ func TestPutFeeAndGasUsedScrNoTx(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(123001460000000), scr.GetFeeInfo().GetFee()) require.Equal(t, uint64(7350146), scr.GetFeeInfo().GetGasUsed()) @@ -203,7 +217,7 @@ func TestPutFeeAndGasUsedInvalidTxs(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(349500000000000), tx.GetFeeInfo().GetFee()) require.Equal(t, tx.GetTxHandler().GetGasLimit(), tx.GetFeeInfo().GetGasUsed()) @@ -284,7 +298,7 @@ func TestPutFeeAndGasUsedLogWithErrorAndInformative(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, tx1.GetTxHandler().GetGasLimit(), tx1.GetFeeInfo().GetGasUsed()) @@ -335,7 +349,7 @@ func TestPutFeeAndGasUsedWrongRelayedTx(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(6103405000000000), initialTx.GetFeeInfo().GetFee()) require.Equal(t, uint64(550000000), initialTx.GetFeeInfo().GetGasUsed()) @@ -370,7 +384,7 @@ func TestPutFeeAndGasUsedESDTWithScCall(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(820765000000000), tx.GetFeeInfo().GetFee()) require.Equal(t, uint64(55_000_000), tx.GetFeeInfo().GetGasUsed()) @@ -425,7 +439,7 @@ func TestPutFeeAndGasUsedScrWithRefundNoTx(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(0), scr.GetFeeInfo().GetFee()) require.Equal(t, uint64(0), scr.GetFeeInfo().GetGasUsed()) @@ -474,7 +488,7 @@ func TestPutFeeAndGasUsedScrWithRefundNotForInitialSender(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(0), scr.GetFeeInfo().GetFee()) require.Equal(t, uint64(0), scr.GetFeeInfo().GetGasUsed()) @@ -522,7 +536,7 @@ func TestPutFeeAndGasUsedScrWithRefund(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, big.NewInt(552865000000000), initialTx.GetFeeInfo().GetFee()) require.Equal(t, uint64(50_336_500), initialTx.GetFeeInfo().GetGasUsed()) @@ -579,7 +593,7 @@ func TestMoveBalanceWithSignalError(t *testing.T) { require.NotNil(t, txsFeeProc) require.Nil(t, err) - err = txsFeeProc.PutFeeAndGasUsed(pool) + err = txsFeeProc.PutFeeAndGasUsed(pool, 0) require.Nil(t, err) require.Equal(t, uint64(225_500), initialTx.GetFeeInfo().GetGasUsed()) } 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/block/preprocess/transactionsV2.go b/process/block/preprocess/transactionsV2.go index 654ff4231a8..6391987983a 100644 --- a/process/block/preprocess/transactionsV2.go +++ b/process/block/preprocess/transactionsV2.go @@ -218,7 +218,7 @@ func (txs *transactions) processTransaction( } if errors.Is(err, process.ErrFailedTransaction) { - log.Debug("transactions.processTransaction", + log.Trace("transactions.processTransaction", "txHash", txHash, "nonce", tx.Nonce, "value", tx.Value, 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 a510447dab2..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,11 +518,6 @@ func (ed *economicsData) ComputeGasUsedAndFeeBasedOnRefundValueInEpoch(tx data.T txFee := ed.ComputeTxFeeInEpoch(tx, epoch) - if len(tx.GetUserTransactions()) > 0 { - gasUnitsUsed := big.NewInt(0).Div(txFee, big.NewInt(0).SetUint64(tx.GetGasPrice())) - return gasUnitsUsed.Uint64(), txFee - } - isPenalizedTooMuchGasFlagEnabled := ed.enableEpochsHandler.IsFlagEnabledInEpoch(common.PenalizedTooMuchGasFlag, epoch) isGasPriceModifierFlagEnabled := ed.enableEpochsHandler.IsFlagEnabledInEpoch(common.GasPriceModifierFlag, epoch) flagCorrectTxFee := !isPenalizedTooMuchGasFlagEnabled && !isGasPriceModifierFlagEnabled diff --git a/process/economics/economicsData_test.go b/process/economics/economicsData_test.go index 5fdb8c369c2..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" @@ -1622,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 07ed7a91896..cd657c3991d 100644 --- a/process/transaction/export_test.go +++ b/process/transaction/export_test.go @@ -57,7 +57,12 @@ func (txProc *txProcessor) ProcessUserTx( relayedNonce uint64, originalTxHash []byte, ) (vmcommon.ReturnCode, error) { - return txProc.processUserTx(originalTx, userTx, relayedTxValue, relayedNonce, originalTxHash) + return txProc.processUserTx( + originalTx, + userTx, + relayedTxValue, + relayedNonce, + originalTxHash) } // ProcessMoveBalanceCostRelayedUserTx calls the un-exported method processMoveBalanceCostRelayedUserTx 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 129ad2c5db8..51910b537e2 100644 --- a/process/transaction/shardProcess.go +++ b/process/transaction/shardProcess.go @@ -38,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 @@ -132,7 +128,6 @@ func NewTxProcessor(args ArgsNewTxProcessor) (*txProcessor, error) { common.RelayedTransactionsFlag, common.RelayedTransactionsV2Flag, common.RelayedNonceFixFlag, - common.RelayedTransactionsV3Flag, common.FixRelayedBaseCostFlag, }) if err != nil { @@ -147,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, @@ -169,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 @@ -253,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) @@ -500,14 +485,28 @@ func (txProc *txProcessor) processMoveBalance( isPayable, err := txProc.scProcessor.IsPayable(tx.SndAddr, tx.RcvAddr) if err != nil { + errRefund := txProc.revertConsumedValueFromSender(tx, acntSrc, isUserTxOfRelayed) + if errRefund != nil { + log.Error("failed to return funds to sender after check if receiver is payable", "error", errRefund) + } return err } if !isPayable { + err = txProc.revertConsumedValueFromSender(tx, acntSrc, isUserTxOfRelayed) + if err != nil { + log.Error("failed to return funds to sender while transferring to non payable sc", "error", err) + } + return process.ErrAccountNotPayable } err = txProc.checkIfValidTxToMetaChain(tx, tx.RcvAddr) if err != nil { + errLocal := txProc.revertConsumedValueFromSender(tx, acntSrc, isUserTxOfRelayed) + if errLocal != nil { + log.Error("failed to return funds to sender while sending invalid tx to metachain", "error", errLocal) + } + return err } @@ -543,6 +542,31 @@ func (txProc *txProcessor) processMoveBalance( return nil } +func (txProc *txProcessor) revertConsumedValueFromSender( + tx *transaction.Transaction, + acntSrc state.UserAccountHandler, + isUserTxOfRelayed bool, +) error { + if !isUserTxOfRelayed { + return nil + } + + if !txProc.enableEpochsHandler.IsFlagEnabled(common.FixRelayedMoveBalanceToNonPayableSCFlag) { + return nil + } + + if check.IfNil(acntSrc) { + return nil + } + + err := acntSrc.AddToBalance(tx.Value) + if err != nil { + return err + } + + return txProc.accounts.SaveAccount(acntSrc) +} + func (txProc *txProcessor) processSCDeployment( tx *transaction.Transaction, acntSrc state.UserAccountHandler, @@ -580,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 } @@ -594,26 +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()) - } - - defer txProc.saveFailedLogsIfNeeded(originalTxHash) - - return txProc.processUserTx(tx, userTx, tx.Value, tx.Nonce, originalTxHash) + return txProc.processUserTx(tx, userTx, tx.Value, tx.Nonce, txHash) } func (txProc *txProcessor) processTxAtRelayer( @@ -621,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 { @@ -664,128 +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 _, innerTx := range innerTxs { - innerTxFee, innerTxRetCode, innerTxErr = txProc.processInnerTx(tx, innerTx, originalTxHash) - 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, -) (*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()) - } - - if check.IfNil(acntSnd) { - return txFee, vmcommon.UserError, txProc.executeFailedRelayedUserTx( - innerTx, - innerTx.RelayerAddr, - big.NewInt(0), - tx.Nonce, - tx, - originalTxHash, - process.ErrRelayedTxV3SenderShardMismatch.Error()) - } - - // 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()) - } - - result, err := txProc.processUserTx(tx, innerTx, tx.Value, tx.Nonce, originalTxHash) - return txFee, result, err -} - func (txProc *txProcessor) processRelayedTxV2( tx *transaction.Transaction, relayerAcnt, acntDst state.UserAccountHandler, @@ -805,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) @@ -832,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]) @@ -932,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}) } @@ -1008,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 { @@ -1136,6 +1008,7 @@ func (txProc *txProcessor) executeFailedRelayedUserTx( originalTxHash []byte, errorMsg string, ) error { + scrForRelayer := &smartContractResult.SmartContractResult{ Nonce: relayedNonce, Value: big.NewInt(0).Set(relayedTxValue), @@ -1183,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 @@ -1217,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 1f077525ae2..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) @@ -3876,11 +3328,81 @@ func TestTxProcessor_AddNonExecutableLog(t *testing.T) { }) } +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) + + tx := transaction.Transaction{} + tx.Nonce = 0 + tx.SndAddr = []byte("SRC") + tx.RcvAddr = []byte("SRC") + tx.Value = big.NewInt(0) + marshalledData, _ := marshaller.Marshal(&innerTx) + tx.Data = []byte("relayedTx@" + hex.EncodeToString(marshalledData)) + + shardCoordinator.ComputeIdCalled = func(address []byte) uint32 { + return 0 + } + + acntSrc := createUserAcc(innerTx.SndAddr) + initialBalance := big.NewInt(100) + _ = acntSrc.AddToBalance(initialBalance) + acntDst := createUserAcc(innerTx.RcvAddr) + + adb := createAccountStub(innerTx.SndAddr, innerTx.RcvAddr, acntSrc, acntDst) + + 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.RelayedTx, process.RelayedTx + } + + return process.MoveBalance, process.MoveBalance + }, + } + args.EnableEpochsHandler = enableEpochsHandlerMock.NewEnableEpochsHandlerStub( + common.RelayedTransactionsFlag, + common.FixRelayedBaseCostFlag, + common.FixRelayedMoveBalanceToNonPayableSCFlag, + ) + args.ScProcessor = &testscommon.SCProcessorMock{ + IsPayableCalled: func(sndAddress, recvAddress []byte) (bool, error) { + 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) + assert.Nil(t, err) + + balance := acntSrc.GetBalance() + require.Equal(t, initialBalance, balance) // disabled economics data, testing only tx.value +} + 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/statusHandler/statusMetricsProvider.go b/statusHandler/statusMetricsProvider.go index 30ead1e5749..8050d335431 100644 --- a/statusHandler/statusMetricsProvider.go +++ b/statusHandler/statusMetricsProvider.go @@ -378,6 +378,7 @@ func (sm *statusMetrics) EnableEpochsMetrics() (map[string]interface{}, error) { enableEpochsMetrics[common.MetricEGLDInMultiTransferEnableEpoch] = sm.uint64Metrics[common.MetricEGLDInMultiTransferEnableEpoch] enableEpochsMetrics[common.MetricCryptoOpcodesV2EnableEpoch] = sm.uint64Metrics[common.MetricCryptoOpcodesV2EnableEpoch] enableEpochsMetrics[common.MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch] = sm.uint64Metrics[common.MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch] + enableEpochsMetrics[common.MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch] = sm.uint64Metrics[common.MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch] numNodesChangeConfig := sm.uint64Metrics[common.MetricMaxNodesChangeEnableEpoch+"_count"] diff --git a/statusHandler/statusMetricsProvider_test.go b/statusHandler/statusMetricsProvider_test.go index 02f33d62549..14b5b5225d3 100644 --- a/statusHandler/statusMetricsProvider_test.go +++ b/statusHandler/statusMetricsProvider_test.go @@ -401,6 +401,7 @@ func TestStatusMetrics_EnableEpochMetrics(t *testing.T) { sm.SetUInt64Value(common.MetricEGLDInMultiTransferEnableEpoch, uint64(4)) sm.SetUInt64Value(common.MetricCryptoOpcodesV2EnableEpoch, uint64(4)) sm.SetUInt64Value(common.MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch, uint64(4)) + sm.SetUInt64Value(common.MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch, uint64(4)) maxNodesChangeConfig := []map[string]uint64{ { @@ -531,6 +532,7 @@ func TestStatusMetrics_EnableEpochMetrics(t *testing.T) { common.MetricEGLDInMultiTransferEnableEpoch: uint64(4), common.MetricCryptoOpcodesV2EnableEpoch: uint64(4), common.MetricMultiESDTNFTTransferAndExecuteByUserEnableEpoch: uint64(4), + common.MetricFixRelayedMoveBalanceToNonPayableSCEnableEpoch: uint64(4), common.MetricMaxNodesChangeEnableEpoch: []map[string]interface{}{ { diff --git a/testscommon/components/components.go b/testscommon/components/components.go index 0e3dcc14cd1..55b09fe99de 100644 --- a/testscommon/components/components.go +++ b/testscommon/components/components.go @@ -687,7 +687,7 @@ func GetStatusComponentsFactoryArgsAndProcessComponents(shardCoordinator shardin { MarshallerType: "json", Mode: "client", - URL: "localhost:12345", + URL: "ws://localhost:12345", RetryDurationInSec: 1, }, }, 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 bb59020bc27..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,7 @@ 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 } // ComputeFeeForProcessing - @@ -228,6 +226,14 @@ func (e *EconomicsHandlerStub) ComputeMoveBalanceFee(tx data.TransactionWithFeeH return big.NewInt(0) } +// ComputeMoveBalanceFeeInEpoch - +func (e *EconomicsHandlerStub) ComputeMoveBalanceFeeInEpoch(tx data.TransactionWithFeeHandler, epoch uint32) *big.Int { + if e.ComputeMoveBalanceFeeInEpochCalled != nil { + return e.ComputeMoveBalanceFeeInEpochCalled(tx, epoch) + } + return big.NewInt(0) +} + // ComputeTxFee - func (e *EconomicsHandlerStub) ComputeTxFee(tx data.TransactionWithFeeHandler) *big.Int { if e.ComputeTxFeeCalled != nil { @@ -359,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 3506d2ba9a7..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 - @@ -27,6 +26,7 @@ type EconomicsHandlerMock struct { ComputeFeeCalled func(tx data.TransactionWithFeeHandler) *big.Int CheckValidityTxValuesCalled func(tx data.TransactionWithFeeHandler) error ComputeMoveBalanceFeeCalled func(tx data.TransactionWithFeeHandler) *big.Int + ComputeMoveBalanceFeeInEpochCalled func(tx data.TransactionWithFeeHandler, epoch uint32) *big.Int ComputeTxFeeCalled func(tx data.TransactionWithFeeHandler) *big.Int DeveloperPercentageCalled func() float64 MinGasPriceCalled func() uint64 @@ -47,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 - @@ -199,7 +197,14 @@ func (ehm *EconomicsHandlerMock) ComputeMoveBalanceFee(tx data.TransactionWithFe return ehm.ComputeMoveBalanceFeeCalled(tx) } return big.NewInt(0) +} +// ComputeMoveBalanceFeeInEpoch - +func (ehm *EconomicsHandlerMock) ComputeMoveBalanceFeeInEpoch(tx data.TransactionWithFeeHandler, epoch uint32) *big.Int { + if ehm.ComputeMoveBalanceFeeInEpochCalled != nil { + return ehm.ComputeMoveBalanceFeeInEpochCalled(tx, epoch) + } + return big.NewInt(0) } // ComputeGasLimitBasedOnBalance - @@ -338,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/esdtStorageHandlerStub.go b/testscommon/esdtStorageHandlerStub.go index 47825717409..599197e7fca 100644 --- a/testscommon/esdtStorageHandlerStub.go +++ b/testscommon/esdtStorageHandlerStub.go @@ -10,7 +10,7 @@ import ( // EsdtStorageHandlerStub - type EsdtStorageHandlerStub struct { - SaveESDTNFTTokenCalled func(senderAddress []byte, acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64, esdtData *esdt.ESDigitalToken, isCreation bool, isReturnWithError bool) ([]byte, error) + SaveESDTNFTTokenCalled func(senderAddress []byte, acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64, esdtData *esdt.ESDigitalToken, saveArgs vmcommon.NftSaveArgs) ([]byte, error) GetESDTNFTTokenOnSenderCalled func(acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64) (*esdt.ESDigitalToken, error) GetESDTNFTTokenOnDestinationCalled func(acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64) (*esdt.ESDigitalToken, bool, error) GetESDTNFTTokenOnDestinationWithCustomSystemAccountCalled func(accnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64, systemAccount vmcommon.UserAccountHandler) (*esdt.ESDigitalToken, bool, error) @@ -18,7 +18,7 @@ type EsdtStorageHandlerStub struct { SaveNFTMetaDataCalled func(tx data.TransactionHandler) error AddToLiquiditySystemAccCalled func(esdtTokenKey []byte, tokenType uint32, nonce uint64, transferValue *big.Int, keepMetadataOnZeroLiquidity bool) error SaveMetaDataToSystemAccountCalled func(tokenKey []byte, nonce uint64, esdtData *esdt.ESDigitalToken) error - GetMetaDataFromSystemAccountCalled func(bytes []byte, u uint64) (*esdt.MetaData, error) + GetMetaDataFromSystemAccountCalled func(bytes []byte, u uint64) (*esdt.ESDigitalToken, error) } // SaveMetaDataToSystemAccount - @@ -31,7 +31,7 @@ func (e *EsdtStorageHandlerStub) SaveMetaDataToSystemAccount(tokenKey []byte, no } // GetMetaDataFromSystemAccount - -func (e *EsdtStorageHandlerStub) GetMetaDataFromSystemAccount(bytes []byte, u uint64) (*esdt.MetaData, error) { +func (e *EsdtStorageHandlerStub) GetMetaDataFromSystemAccount(bytes []byte, u uint64) (*esdt.ESDigitalToken, error) { if e.GetMetaDataFromSystemAccountCalled != nil { return e.GetMetaDataFromSystemAccountCalled(bytes, u) } @@ -40,9 +40,9 @@ func (e *EsdtStorageHandlerStub) GetMetaDataFromSystemAccount(bytes []byte, u ui } // SaveESDTNFTToken - -func (e *EsdtStorageHandlerStub) SaveESDTNFTToken(senderAddress []byte, acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64, esdtData *esdt.ESDigitalToken, isCreation bool, isReturnWithError bool) ([]byte, error) { +func (e *EsdtStorageHandlerStub) SaveESDTNFTToken(senderAddress []byte, acnt vmcommon.UserAccountHandler, esdtTokenKey []byte, nonce uint64, esdtData *esdt.ESDigitalToken, saveArgs vmcommon.NftSaveArgs) ([]byte, error) { if e.SaveESDTNFTTokenCalled != nil { - return e.SaveESDTNFTTokenCalled(senderAddress, acnt, esdtTokenKey, nonce, esdtData, isCreation, isReturnWithError) + return e.SaveESDTNFTTokenCalled(senderAddress, acnt, esdtTokenKey, nonce, esdtData, saveArgs) } return nil, nil diff --git a/testscommon/feeComputerStub.go b/testscommon/feeComputerStub.go index 33dcfbb4e4b..884351576d9 100644 --- a/testscommon/feeComputerStub.go +++ b/testscommon/feeComputerStub.go @@ -12,6 +12,7 @@ type FeeComputerStub struct { ComputeGasUsedAndFeeBasedOnRefundValueCalled func(tx *transaction.ApiTransactionResult, refundValue *big.Int) (uint64, *big.Int) ComputeTxFeeBasedOnGasUsedCalled func(tx *transaction.ApiTransactionResult, gasUsed uint64) *big.Int ComputeGasLimitCalled func(tx *transaction.ApiTransactionResult) uint64 + ComputeMoveBalanceFeeCalled func(tx *transaction.ApiTransactionResult) *big.Int } // ComputeTransactionFee - @@ -49,6 +50,15 @@ func (stub *FeeComputerStub) ComputeGasLimit(tx *transaction.ApiTransactionResul return 0 } +// ComputeMoveBalanceFee - +func (stub *FeeComputerStub) ComputeMoveBalanceFee(tx *transaction.ApiTransactionResult) *big.Int { + if stub.ComputeMoveBalanceFeeCalled != nil { + return stub.ComputeMoveBalanceFeeCalled(tx) + } + + return big.NewInt(0) +} + // IsInterfaceNil returns true if there is no value under the interface func (stub *FeeComputerStub) IsInterfaceNil() bool { return false 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, - }, } } 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{