From ad4268c2ec8a0451f8ab07a72f9321c40cdde601 Mon Sep 17 00:00:00 2001 From: Vaibhav Srivastava Date: Thu, 3 Sep 2026 15:42:40 +0530 Subject: [PATCH 1/8] docs: fix typo defualt -> default (#6933) Signed-off-by: Vaibhav Srivastava --- common/src/main/java/org/tron/core/config/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/main/java/org/tron/core/config/README.md b/common/src/main/java/org/tron/core/config/README.md index 5618cb9fed9..6bcd2ade1aa 100644 --- a/common/src/main/java/org/tron/core/config/README.md +++ b/common/src/main/java/org/tron/core/config/README.md @@ -20,7 +20,7 @@ storage { # block_KDB, peers, properties, recent-block, trans, # utxo, votes, witness, witness_schedule. - # Otherwise, db configs will remain defualt and data will be stored in + # Otherwise, db configs will remain default and data will be stored in # the path of "output-directory" or which is set by "-d" ("--output-directory"). # Attention: name is a required field that must be set !!! From 57b7b04f385bc5da1a417b0af75aaca200f41336 Mon Sep 17 00:00:00 2001 From: GrothenDI Date: Thu, 3 Sep 2026 18:14:14 +0800 Subject: [PATCH 2/8] docs: clarify outdated code comments (#6914) Clarify trigger behavior, log retention, Solidity API availability, and account-name rules. --- .../main/java/org/tron/common/logsfilter/TriggerConfig.java | 2 +- .../http/solidity/HttpApiOnSolidityService.java | 1 - framework/src/main/resources/logback.xml | 2 +- protocol/src/main/protos/core/contract/account_contract.proto | 3 +-- 4 files changed, 3 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java b/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java index d76db47c40d..bf4b1cd4946 100644 --- a/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java +++ b/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java @@ -33,7 +33,7 @@ public TriggerConfig() { triggerName = ""; enabled = false; topic = ""; - redundancy = false; // event will also write to log + redundancy = false; // if true, event triggers will also be emitted as log triggers ethCompatible = false; // add eth compatible fields, just for transaction now solidified = false; // just write solidified data, just for block and transaction now } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java index 33e325bd578..b7e96a36b45 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java @@ -265,7 +265,6 @@ protected void addServlet(ServletContextHandler context) { context.addServlet(new ServletHolder(getMarketPairListOnSolidityServlet), "/walletsolidity/getmarketpairlist"); - // only for SolidityNode context.addServlet(new ServletHolder(getTransactionByIdOnSolidityServlet), "/walletsolidity/gettransactionbyid"); context.addServlet(new ServletHolder(getTransactionInfoByIdOnSolidityServlet), diff --git a/framework/src/main/resources/logback.xml b/framework/src/main/resources/logback.xml index 1b0955df2fd..1c50b65e518 100644 --- a/framework/src/main/resources/logback.xml +++ b/framework/src/main/resources/logback.xml @@ -31,7 +31,7 @@ class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> ./logs/tron-%d{yyyy-MM-dd}.%i.log.gz - + 500MB 7 50GB diff --git a/protocol/src/main/protos/core/contract/account_contract.proto b/protocol/src/main/protos/core/contract/account_contract.proto index d3180048f43..05e7226329c 100644 --- a/protocol/src/main/protos/core/contract/account_contract.proto +++ b/protocol/src/main/protos/core/contract/account_contract.proto @@ -29,7 +29,7 @@ message AccountCreateContract { AccountType type = 3; } -// Update account name. Account name is not unique now. +// Update account name. ALLOW_UPDATE_ACCOUNT_NAME is not enabled on Mainnet, so account names are currently unique. message AccountUpdateContract { bytes account_name = 1; bytes owner_address = 2; @@ -47,4 +47,3 @@ message AccountPermissionUpdateContract { Permission witness = 3; //Can be empty repeated Permission actives = 4; //Empty is invalidate } - From bd2450fe063c46a201df71594f91e9f8fc4308bb Mon Sep 17 00:00:00 2001 From: Evan Date: Tue, 8 Sep 2026 20:35:20 +0800 Subject: [PATCH 3/8] feat(version): merge release_v4.8.2.2 into master (#6952) * feat: optimize delegate and undelegate instruction handling (#6920) Co-authored-by: Asuka * perf: optimize jump table initialization and reuse (#6943) Co-authored-by: Asuka * feat: refine contract deployment transaction validation (#6945) Co-authored-by: Asuka * ci: run single-node smoke only and disable multinode (backport #6908 to release_v4.8.2.2) (#6953) Backport of #6908 to the release_v4.8.2.2 branch so CI passes there: - Switch the single-node integration CI to the smoke test subset (--clean --smoke instead of the full suite), renaming workflow, job, steps, and report artifact from "Full" to "Smoke" - Remove the multinode integration CI workflow entirely; the full single-node suite and the multinode suite are unstable in CI today (hardened assertions don't match the troninfra/troninfra-ci image fixture), causing failures unrelated to PR code --------- Co-authored-by: ouy95917 Co-authored-by: Asuka Co-authored-by: Jeremy Zhang <50477615+warku123@users.noreply.github.com> --- .../workflows/integration-test-multinode.yml | 119 ----------- .../integration-test-single-node.yml | 14 +- .../org/tron/core/actuator/VMActuator.java | 31 ++- .../main/java/org/tron/core/vm/Operation.java | 8 + .../org/tron/core/vm/OperationRegistry.java | 187 +++++++++--------- .../CancelAllUnfreezeV2Processor.java | 5 + .../FreezeBalanceV2Processor.java | 5 + .../UnfreezeBalanceV2Processor.java | 5 + .../WithdrawExpireUnfreezeProcessor.java | 5 + .../tron/core/vm/program/ContractState.java | 10 + .../org/tron/core/vm/program/Program.java | 17 +- .../tron/core/vm/repository/Repository.java | 4 + .../core/vm/repository/RepositoryImpl.java | 31 +++ .../java/org/tron/core/vm/utils/MUtil.java | 25 +++ .../org/tron/core/capsule/AccountCapsule.java | 4 + .../java/org/tron/core/config/Parameter.java | 5 +- .../common/runtime/VMActuatorMockTest.java | 55 +++++- .../common/runtime/vm/OperationsTest.java | 34 +++- .../runtime/vm/VoteWitnessCost3Test.java | 4 +- .../actuator/ContractHashValidationTest.java | 67 +++++++ .../actuator/ContractNameValidationTest.java | 65 ++++++ .../tron/core/vm/OperationRegistryTest.java | 142 +++++++++++++ .../StakeV2AfterSelfDestructTest.java | 186 +++++++++++++++++ .../RepositoryImplSelfDestructTest.java | 36 ++++ 24 files changed, 830 insertions(+), 234 deletions(-) delete mode 100644 .github/workflows/integration-test-multinode.yml create mode 100644 framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java create mode 100644 framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java create mode 100644 framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java create mode 100644 framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java create mode 100644 framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java diff --git a/.github/workflows/integration-test-multinode.yml b/.github/workflows/integration-test-multinode.yml deleted file mode 100644 index fadfc2168d2..00000000000 --- a/.github/workflows/integration-test-multinode.yml +++ /dev/null @@ -1,119 +0,0 @@ -name: Integration Test Multinode (Full) - -on: - push: - branches: [ 'master', 'release_**' ] - pull_request: - branches: [ 'develop', 'release_**' ] - types: [ opened, synchronize, reopened ] - paths-ignore: [ '**/*.md', '.gitignore', '**/.gitignore', '.editorconfig', - '.gitattributes', 'docs/**', 'CHANGELOG', '.github/ISSUE_TEMPLATE/**', - '.github/PULL_REQUEST_TEMPLATE/**', '.github/CODEOWNERS' ] - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - multinode-full: - name: Integration Test Multinode Full (JDK 8 / x86_64) - runs-on: ubuntu-latest - timeout-minutes: 60 - - steps: - - name: Checkout java-tron - uses: actions/checkout@v5 - - - name: Set up JDK 8 - uses: actions/setup-java@v5 - with: - java-version: '8' - distribution: 'temurin' - - - name: Cache Gradle packages - uses: actions/cache@v5 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-multinode-${{ hashFiles('**/*.gradle', '**/gradle-wrapper.properties') }} - restore-keys: ${{ runner.os }}-gradle-multinode- - - - name: Build FullNode.jar - run: ./gradlew clean build -x test --no-daemon - - - name: Build local java-tron Docker image (wraps PR-built FullNode.jar) - run: | - mkdir -p /tmp/tron-image - cp build/libs/FullNode.jar /tmp/tron-image/ - cat > /tmp/tron-image/Dockerfile <<'EOF' - FROM tronprotocol/java-tron:latest - COPY FullNode.jar /java-tron/lib/FullNode.jar - EOF - docker build -t java-tron-local:pr /tmp/tron-image - - - name: Pull integration-test image - run: docker pull troninfra/troninfra-ci:latest - - - name: Extract compose configs to host (for DinD path-alignment) - run: | - # start-multinode.sh builds HOST_COMPOSE_DIR as: - # ${HOST_WORKDIR}/docker/multi-node - # so the files must live at $HOST_WORKDIR/docker/multi-node/ on the - # host. Set HOST_WORKDIR to the workspace root and extract - # /app/docker/ 1:1 into workspace/docker/ — the subdirectories - # (multi-node/, single-node/) don't collide with java-tron's own - # docker/ files. - docker create --name it-extract troninfra/troninfra-ci:latest - docker cp it-extract:/app/docker/. "${{ github.workspace }}/docker/" - docker rm -f it-extract - - - name: Run multinode full tests - run: | - # --network host: multinode tests talk to nodes via 127.0.0.1:50051 etc. - # DinD socket + HOST_WORKDIR path-alignment lets the container orchestrate - # the 3-witness compose stack via the host daemon. - # Don't override --workdir so the container's default /app entrypoint works. - docker run --name integration-multinode \ - --network host \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v "${{ github.workspace }}:${{ github.workspace }}" \ - -v "${{ github.workspace }}/docker/multi-node:/app/docker/multi-node" \ - -e HOST_WORKDIR="${{ github.workspace }}" \ - -e TRON_IMAGE=java-tron-local:pr \ - -e JAVA_HOME=/usr/lib/jvm/temurin-8 \ - -e JAVA_HOME_17=/opt/java/openjdk \ - troninfra/troninfra-ci:latest \ - --multinode --clean - - - name: Extract test reports from container - if: always() - run: | - mkdir -p integration-reports - docker cp integration-multinode:/app/build/reports/. integration-reports/reports/ 2>/dev/null || true - docker cp integration-multinode:/app/build/test-results/. integration-reports/test-results/ 2>/dev/null || true - docker cp integration-multinode:/app/build/test-output.log integration-reports/ 2>/dev/null || true - - - name: Collect witness node logs - if: always() - run: | - mkdir -p integration-reports/node-logs - for c in tron-mn-node1 tron-mn-node2 tron-mn-node3 tron-mn-mongodb; do - docker logs "$c" > "integration-reports/node-logs/${c}.log" 2>&1 || true - done - - - name: Tear down compose stack - if: always() - run: | - docker rm -f tron-mn-node1 tron-mn-node2 tron-mn-node3 tron-mn-mongodb 2>/dev/null || true - docker network rm multi-node_tron-net 2>/dev/null || true - docker rm -f integration-multinode 2>/dev/null || true - - - name: Upload test reports - if: always() - uses: actions/upload-artifact@v6 - with: - name: integration-multinode-report - path: integration-reports/ - if-no-files-found: warn diff --git a/.github/workflows/integration-test-single-node.yml b/.github/workflows/integration-test-single-node.yml index b0c10247a7f..3c56843c799 100644 --- a/.github/workflows/integration-test-single-node.yml +++ b/.github/workflows/integration-test-single-node.yml @@ -1,4 +1,4 @@ -name: Integration Test Single Node (Full) +name: Integration Test Single Node (Smoke) on: push: @@ -17,7 +17,7 @@ concurrency: jobs: integration: - name: Integration Test Single Node Full (JDK 8 / x86_64) + name: Integration Test Single Node Smoke (JDK 8 / x86_64) runs-on: ubuntu-latest timeout-minutes: 45 @@ -46,7 +46,7 @@ jobs: - name: Pull integration-test image run: docker pull troninfra/troninfra-ci:latest - - name: Run integration tests + - name: Run integration smoke tests run: | # JAVA_HOME=JDK 8 so FullNode runs on the same JVM family as # production (a few assertions check `java.version` starts with @@ -58,9 +58,9 @@ jobs: -e JAVA_HOME_17=/opt/java/openjdk \ -v "${{ github.workspace }}/build/libs/FullNode.jar:/javatron/FullNode.jar:ro" \ troninfra/troninfra-ci:latest \ - --clean + --clean --smoke - - name: Extract test reports from container + - name: Extract smoke test reports from container if: always() run: | mkdir -p integration-reports @@ -71,10 +71,10 @@ jobs: docker cp integration-test:/app/node/data/logs/tron.log integration-reports/ 2>/dev/null || true docker rm -f integration-test 2>/dev/null || true - - name: Upload test reports + - name: Upload smoke test reports if: always() uses: actions/upload-artifact@v6 with: - name: integration-test-report + name: integration-smoke-test-report path: integration-reports/ if-no-files-found: warn diff --git a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java index d785951027b..e0a721db28d 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -25,6 +25,7 @@ import org.tron.common.runtime.InternalTransaction.TrxType; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.vm.DataWord; +import org.tron.common.utils.ForkController; import org.tron.common.utils.StorageUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; @@ -33,6 +34,7 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.ReceiptCapsule; +import org.tron.core.config.Parameter; import org.tron.core.db.EnergyProcessor; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; @@ -189,7 +191,8 @@ public void execute(Object object) throws ContractExeException { throw e; } - VM.play(program, OperationRegistry.getTable()); + // Prepare the table once for this execution and all nested calls. + VM.play(program, OperationRegistry.prepareAndGetTable(isConstantCall)); result = program.getResult(); if (VMConfig.allowEnergyAdjustment()) { @@ -217,6 +220,9 @@ public void execute(Object object) throws ContractExeException { } else { result.spendEnergy(saveCodeEnergy); if (VMConfig.allowTvmConstantinople()) { + CreateSmartContract createContract = + ContractCapsule.getSmartContractFromTransaction(trx); + checkContractHashFields(createContract.getNewContract()); rootRepository.saveCode(program.getContractAddress().getNoLeadZeroesData(), code); } } @@ -330,6 +336,7 @@ private void create() if (contract == null) { throw new ContractValidateException("Cannot get CreateSmartContract from transaction"); } + SmartContract newSmartContract; if (VMConfig.allowTvmCompatibleEvm()) { newSmartContract = contract.getNewContract().toBuilder().setVersion(1).build(); @@ -341,11 +348,7 @@ private void create() throw new ContractValidateException("OwnerAddress is not equals OriginAddress"); } - byte[] contractName = newSmartContract.getName().getBytes(); - - if (contractName.length > VMConstant.CONTRACT_NAME_LENGTH) { - throw new ContractValidateException("contractName's length cannot be greater than 32"); - } + checkContractNameLength(contract.getNewContract()); long percent = contract.getNewContract().getConsumeUserResourcePercent(); if (percent < 0 || percent > VMConstant.ONE_HUNDRED) { @@ -455,6 +458,22 @@ private void create() } + static void checkContractHashFields(SmartContract contract) { + if (!contract.getCodeHash().isEmpty() || !contract.getTrxHash().isEmpty()) { + MUtil.checkCPUTimeForContractHashFields(); + } + } + + static void checkContractNameLength(SmartContract contract) throws ContractValidateException { + int contractNameLength = + ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2) + ? contract.getNameBytes().size() + : contract.getName().getBytes().length; + if (contractNameLength > VMConstant.CONTRACT_NAME_LENGTH) { + throw new ContractValidateException("contractName's length cannot be greater than 32"); + } + } + /** * ** */ diff --git a/actuator/src/main/java/org/tron/core/vm/Operation.java b/actuator/src/main/java/org/tron/core/vm/Operation.java index 87ff8fce749..80b25262089 100644 --- a/actuator/src/main/java/org/tron/core/vm/Operation.java +++ b/actuator/src/main/java/org/tron/core/vm/Operation.java @@ -52,4 +52,12 @@ public void execute(Program program) { public boolean isEnabled() { return enabled.getAsBoolean(); } + + public Operation adjustCost(Function newCost) { + return new Operation(opcode, require, ret, newCost, action, enabled); + } + + public Operation adjustAction(Consumer newAction) { + return new Operation(opcode, require, ret, cost, newAction, enabled); + } } diff --git a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java index 8c078e843a2..28ce2147beb 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java @@ -7,12 +7,45 @@ public class OperationRegistry { + private static final Operation DEFAULT_MLOAD = new Operation( + Op.MLOAD, 1, 1, EnergyCost::getMloadCost, OperationActions::mLoadAction); + + private static final Operation DEFAULT_MSTORE = new Operation( + Op.MSTORE, 2, 0, EnergyCost::getMStoreCost, OperationActions::mStoreAction); + + private static final Operation DEFAULT_MSTORE8 = new Operation( + Op.MSTORE8, 2, 0, EnergyCost::getMStore8Cost, OperationActions::mStore8Action); + + private static final Operation ADJUSTED_MLOAD = + DEFAULT_MLOAD.adjustCost(EnergyCost::getMloadCost2); + + private static final Operation ADJUSTED_MSTORE = + DEFAULT_MSTORE.adjustCost(EnergyCost::getMStoreCost2); + + private static final Operation ADJUSTED_MSTORE8 = + DEFAULT_MSTORE8.adjustCost(EnergyCost::getMStore8Cost2); + + private static final Operation DEFAULT_VOTEWITNESS = new Operation( + Op.VOTEWITNESS, 4, 1, EnergyCost::getVoteWitnessCost, + OperationActions::voteWitnessAction, VMConfig::allowTvmVote); + + private static final Operation ADJUSTED_VOTEWITNESS = + DEFAULT_VOTEWITNESS.adjustCost(EnergyCost::getVoteWitnessCost2); + + private static final Operation OSAKA_VOTEWITNESS = + DEFAULT_VOTEWITNESS.adjustCost(EnergyCost::getVoteWitnessCost3); + + private static final Operation DEFAULT_SUICIDE = new Operation( + Op.SUICIDE, 1, 0, EnergyCost::getSuicideCost, OperationActions::suicideAction); + + private static final Operation ADJUSTED_SUICIDE = + DEFAULT_SUICIDE.adjustCost(EnergyCost::getSuicideCost2); + + private static final Operation RESTRICTED_SUICIDE = + DEFAULT_SUICIDE.adjustCost(EnergyCost::getSuicideCost3) + .adjustAction(OperationActions::suicideAction2); + public enum Version { - TRON_V1_0, - TRON_V1_1, - TRON_V1_2, - TRON_V1_3, - TRON_V1_4, TRON_V1_5, // add more // TRON_V2, @@ -21,13 +54,21 @@ public enum Version { private static final Map tableMap = new HashMap<>(); + // The newest version in use. Bump this when a newer operation set is added, + // together with newLatestOperationSet() below. + private static final Version LATEST_VERSION = Version.TRON_V1_5; + static { - tableMap.put(Version.TRON_V1_0, newTronV10OperationSet()); - tableMap.put(Version.TRON_V1_1, newTronV11OperationSet()); - tableMap.put(Version.TRON_V1_2, newTronV12OperationSet()); - tableMap.put(Version.TRON_V1_3, newTronV13OperationSet()); - tableMap.put(Version.TRON_V1_4, newTronV14OperationSet()); - tableMap.put(Version.TRON_V1_5, newTronV15OperationSet()); + tableMap.put(LATEST_VERSION, newLatestOperationSet()); + } + + // Constant calls get a dedicated instance of the newest table, isolated from + // the shared consensus table above. + private static final JumpTable CONSTANT_CALL_TABLE = newLatestOperationSet(); + + // The single place that decides which operation set is the newest. + private static JumpTable newLatestOperationSet() { + return newTronV15OperationSet(); } public static JumpTable newTronV10OperationSet() { @@ -74,28 +115,22 @@ public static JumpTable newTronV15OperationSet() { // Just for warming up class to avoid out_of_time public static void init() {} - public static JumpTable getTable() { - // always get the table which has the newest version - JumpTable table = tableMap.get(Version.TRON_V1_5); - - // next make the corresponding changes, exclude activating opcode - if (VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx()) { - adjustMemOperations(table); - } - - if (VMConfig.allowEnergyAdjustment()) { - adjustForFairEnergy(table); - } - - if (VMConfig.allowTvmSelfdestructRestriction()) { - adjustSelfdestruct(table); - } + public static JumpTable prepareAndGetTable(boolean isConstantCall) { + JumpTable table = getTable(isConstantCall); + // Apply configuration-dependent changes once at the top level. + adjustTable(table); + return table; + } - if (VMConfig.allowTvmOsaka()) { - adjustVoteWitnessCost(table); - } + public static JumpTable getTable(boolean isConstantCall) { + return isConstantCall ? CONSTANT_CALL_TABLE : tableMap.get(LATEST_VERSION); + } - return table; + private static void adjustTable(JumpTable table) { + // Make the corresponding changes, excluding opcode activation. + adjustMemOperations(table); + adjustVoteWitness(table); + adjustSelfdestruct(table); } public static JumpTable newBaseOperationSet() { @@ -331,20 +366,11 @@ public static JumpTable newBaseOperationSet() { EnergyCost::getBaseTierCost, OperationActions::popAction)); - table.set(new Operation( - Op.MLOAD, 1, 1, - EnergyCost::getMloadCost, - OperationActions::mLoadAction)); + table.set(DEFAULT_MLOAD); - table.set(new Operation( - Op.MSTORE, 2, 0, - EnergyCost::getMStoreCost, - OperationActions::mStoreAction)); + table.set(DEFAULT_MSTORE); - table.set(new Operation( - Op.MSTORE8, 2, 0, - EnergyCost::getMStore8Cost, - OperationActions::mStore8Action)); + table.set(DEFAULT_MSTORE8); table.set(new Operation( Op.SLOAD, 1, 1, @@ -449,10 +475,7 @@ public static JumpTable newBaseOperationSet() { EnergyCost::getRevertCost, OperationActions::revertAction)); - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost, - OperationActions::suicideAction)); + table.set(DEFAULT_SUICIDE); return table; } @@ -570,11 +593,7 @@ public static void appendFreezeOperations(JumpTable table) { public static void appendVoteOperations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmVote; - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost, - OperationActions::voteWitnessAction, - proposal)); + table.set(DEFAULT_VOTEWITNESS); table.set(new Operation( Op.WITHDRAWREWARD, 0, 1, @@ -593,23 +612,6 @@ public static void appendLondonOperations(JumpTable table) { proposal)); } - public static void adjustMemOperations(JumpTable table) { - table.set(new Operation( - Op.MLOAD, 1, 1, - EnergyCost::getMloadCost2, - OperationActions::mLoadAction)); - - table.set(new Operation( - Op.MSTORE, 2, 0, - EnergyCost::getMStoreCost2, - OperationActions::mStoreAction)); - - table.set(new Operation( - Op.MSTORE8, 2, 0, - EnergyCost::getMStore8Cost2, - OperationActions::mStore8Action)); - } - public static void appendFreezeV2Operations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmFreezeV2; @@ -664,19 +666,6 @@ public static void appendShangHaiOperations(JumpTable table) { proposal)); } - public static void adjustForFairEnergy(JumpTable table) { - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost2, - OperationActions::voteWitnessAction, - VMConfig::allowTvmVote)); - - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost2, - OperationActions::suicideAction)); - } - public static void appendCancunOperations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmCancun; BooleanSupplier tvmBlobProposal = VMConfig::allowTvmBlob; @@ -722,18 +711,30 @@ public static void appendOsakaOperations(JumpTable table) { proposal)); } - public static void adjustSelfdestruct(JumpTable table) { - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost3, - OperationActions::suicideAction2)); + public static void adjustMemOperations(JumpTable table) { + boolean adjusted = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + table.set(adjusted ? ADJUSTED_MLOAD : DEFAULT_MLOAD); + table.set(adjusted ? ADJUSTED_MSTORE : DEFAULT_MSTORE); + table.set(adjusted ? ADJUSTED_MSTORE8 : DEFAULT_MSTORE8); } - public static void adjustVoteWitnessCost(JumpTable table) { - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost3, - OperationActions::voteWitnessAction, - VMConfig::allowTvmVote)); + public static void adjustVoteWitness(JumpTable table) { + if (VMConfig.allowTvmOsaka()) { + table.set(OSAKA_VOTEWITNESS); + } else if (VMConfig.allowEnergyAdjustment()) { + table.set(ADJUSTED_VOTEWITNESS); + } else { + table.set(DEFAULT_VOTEWITNESS); + } + } + + public static void adjustSelfdestruct(JumpTable table) { + if (VMConfig.allowTvmSelfdestructRestriction()) { + table.set(RESTRICTED_SUICIDE); + } else if (VMConfig.allowEnergyAdjustment()) { + table.set(ADJUSTED_SUICIDE); + } else { + table.set(DEFAULT_SUICIDE); + } } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java index ec1f4363205..6ee8b1245ce 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java @@ -19,6 +19,7 @@ import org.tron.core.vm.VMConstant; import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.protos.Protocol; @Slf4j(topic = "VMProcessor") @@ -39,6 +40,10 @@ public void validate(CancelAllUnfreezeV2Param param, Repository repo) throws Con throw new ContractValidateException( ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } public Map execute(CancelAllUnfreezeV2Param param, Repository repo) throws ContractExeException { diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java index e7e932194ed..96c6e936b36 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java @@ -14,6 +14,7 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; @Slf4j(topic = "VMProcessor") public class FreezeBalanceV2Processor { @@ -63,6 +64,10 @@ public void validate(FreezeBalanceV2Param param, Repository repo) throws Contrac "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } } + + if (repo.isSelfDestructed(ownerAddress)) { + MUtil.checkCPUTimeForFreezeV2AfterSelfDestruct(); + } } public void execute(FreezeBalanceV2Param param, Repository repo) { diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java index af2cbf63a43..73ffb5f294b 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java @@ -23,6 +23,7 @@ import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.nativecontract.param.UnfreezeBalanceV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.core.vm.utils.VoteRewardUtil; import org.tron.protos.Protocol; import org.tron.protos.contract.Common; @@ -86,6 +87,10 @@ public void validate(UnfreezeBalanceV2Param param, Repository repo) throw new ContractValidateException( "Invalid unfreeze_balance, [" + param.getUnfreezeBalance() + "] is invalid"); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } private boolean checkUnfreezeBalance( diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java index 0bcdb10d46f..982031aa672 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java @@ -17,6 +17,7 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.protos.Protocol; @Slf4j(topic = "VMProcessor") @@ -52,6 +53,10 @@ public void validate(WithdrawExpireUnfreezeParam param, Repository repo) throws logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } private long getTotalWithdrawUnfreeze(List unfrozenV2List, long now) { diff --git a/actuator/src/main/java/org/tron/core/vm/program/ContractState.java b/actuator/src/main/java/org/tron/core/vm/program/ContractState.java index c6347b9a072..30ec0d24f34 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/ContractState.java +++ b/actuator/src/main/java/org/tron/core/vm/program/ContractState.java @@ -131,6 +131,16 @@ public boolean isNewContract(byte[] address) { return repository.isNewContract(address); } + @Override + public void markSelfDestruct(byte[] address) { + repository.markSelfDestruct(address); + } + + @Override + public boolean isSelfDestructed(byte[] address) { + return repository.isSelfDestructed(address); + } + @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { repository.updateAccount(address, accountCapsule); diff --git a/actuator/src/main/java/org/tron/core/vm/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index 590859a9fef..2be1eb80703 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Program.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Program.java @@ -512,12 +512,18 @@ public void suicide(DataWord obtainerAddress) { internalTx.setValue(internalTx.getValue() + expireUnfrozenBalance); } } + + getContractState().markSelfDestruct(owner); getResult().addDeleteAccount(this.getContractAddress()); } public void suicide2(DataWord obtainerAddress) { - byte[] owner = getContextAddress(); + + if (getContractState().isSelfDestructed(obtainerAddress.toTronAddress())) { + MUtil.checkCPUTimeForSelfDestructedBeneficiary(); + } + boolean isNewContract = getContractState().isNewContract(owner); if (isNewContract) { suicide(obtainerAddress); @@ -540,6 +546,7 @@ public void suicide2(DataWord obtainerAddress) { "suicide", nonce, getContractState().getAccount(owner).getAssetMapV2()); if (FastByteComparisons.isEqual(owner, obtainer)) { + getContractState().markSelfDestruct(owner); return; } @@ -579,6 +586,8 @@ public void suicide2(DataWord obtainerAddress) { internalTx.setValue(internalTx.getValue() + expireUnfrozenBalance); } } + + getContractState().markSelfDestruct(owner); } public Repository getContractState() { @@ -914,7 +923,8 @@ this, new DataWord(newAddress), getContractAddress(), value, DataWord.ZERO(), if (VMConfig.allowTvmCompatibleEvm()) { program.setContractVersion(getContractVersion()); } - VM.play(program, OperationRegistry.getTable()); + // Reuse the table prepared by the top-level execution. + VM.play(program, OperationRegistry.getTable(isConstantCall())); createResult = program.getResult(); getTrace().merge(program.getTrace()); // always commit nonce @@ -1146,7 +1156,8 @@ this, new DataWord(contextAddress), program.setContractVersion(invoke.getDeposit() .getContract(codeAddress).getContractVersion()); } - VM.play(program, OperationRegistry.getTable()); + // Reuse the table prepared by the top-level execution. + VM.play(program, OperationRegistry.getTable(isConstantCall())); callResult = program.getResult(); getTrace().merge(program.getTrace()); diff --git a/actuator/src/main/java/org/tron/core/vm/repository/Repository.java b/actuator/src/main/java/org/tron/core/vm/repository/Repository.java index 8f91d59d0b8..ab86328c428 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/Repository.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/Repository.java @@ -59,6 +59,10 @@ public interface Repository { boolean isNewContract(byte[] address); + void markSelfDestruct(byte[] address); + + boolean isSelfDestructed(byte[] address); + void updateAccount(byte[] address, AccountCapsule accountCapsule); void updateDynamicProperty(byte[] word, BytesCapsule bytesCapsule); diff --git a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java index 62e7ce6ec08..7801a18798a 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java @@ -139,6 +139,7 @@ public class RepositoryImpl implements Repository { private final HashMap> delegatedResourceAccountIndexCache = new HashMap<>(); private final HashBasedTable> transientStorage = HashBasedTable.create(); private final HashSet newContractCache = new HashSet<>(); + private final HashSet selfDestructCache = new HashSet<>(); public static void removeLruCache(byte[] address) { } @@ -572,6 +573,29 @@ public boolean isNewContract(byte[] address) { } } + @Override + public void markSelfDestruct(byte[] address) { + selfDestructCache.add(Key.create(address)); + } + + @Override + public boolean isSelfDestructed(byte[] address) { + Key key = Key.create(address); + if (selfDestructCache.contains(key)) { + return true; + } + + if (parent != null) { + boolean isSelfDestructed = parent.isSelfDestructed(address); + if (isSelfDestructed) { + selfDestructCache.add(key); + } + return isSelfDestructed; + } else { + return false; + } + } + @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { accountCache.put(Key.create(address), @@ -780,6 +804,7 @@ public void commit() { commitDelegatedResourceAccountIndexCache(repository); commitTransientStorage(repository); commitNewContractCache(repository); + commitSelfDestructCache(repository); } @Override @@ -1142,6 +1167,12 @@ public void commitNewContractCache(Repository deposit) { } } + private void commitSelfDestructCache(Repository deposit) { + if (deposit != null) { + selfDestructCache.forEach(key -> deposit.markSelfDestruct(key.getData())); + } + } + /** * Get the block id from the number. */ diff --git a/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java b/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java index e07360e6863..c7059016b88 100644 --- a/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java +++ b/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java @@ -59,6 +59,12 @@ public static boolean isNotNullOrEmpty(String str) { return !isNullOrEmpty(str); } + public static void checkCPUTimeForContractHashFields() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for contract hash fields"); + } + } + public static void checkCPUTime() { if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_7_1)) { throw new OutOfTimeException("CPU timeout for 0x0a executing"); @@ -76,4 +82,23 @@ public static void checkCPUTimeForModExp() { throw new OutOfTimeException("CPU timeout for modExp executing"); } } + + public static void checkCPUTimeForFreezeV2AfterSelfDestruct() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for FreezeBalanceV2 after SELFDESTRUCT"); + } + } + + public static void checkCPUTimeForSelfDestructedBeneficiary() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException( + "CPU timeout for SELFDESTRUCT with selfdestructed beneficiary"); + } + } + + public static void checkCPUTimeForInvalidDelegatedV2Balance() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for invalid delegated V2 balance"); + } + } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java index 1af7b55c8b2..026dce74ec8 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -1336,6 +1336,10 @@ public void clearDelegatedResource() { this.account = builder.build(); } + public boolean hasInvalidDelegatedV2() { + return getDelegatedFrozenV2BalanceForBandwidth() < 0 || getDelegatedFrozenV2BalanceForEnergy() < 0; + } + public void importAsset(byte[] key) { this.account = AssetUtil.importAsset(this.account, key); } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index 233f1d9ef7a..0f9402641e9 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -30,7 +30,8 @@ public enum ForkBlockVersionEnum { VERSION_4_8_0_1(33, 1596780000000L, 70), VERSION_4_8_1(34, 1596780000000L, 80), VERSION_4_8_1_1(35, 1596780000000L, 70), - VERSION_4_8_2(36, 1596780000000L, 80); + VERSION_4_8_2(36, 1596780000000L, 80), + VERSION_4_8_2_2(37, 1596780000000L, 70); // if add a version, modify BLOCK_VERSION simultaneously @Getter @@ -79,7 +80,7 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 36; + public static final int BLOCK_VERSION = 37; public static final long FROZEN_PERIOD = 86_400_000L; public static final long DELEGATE_PERIOD = 3 * 86_400_000L; public static final long TRX_PRECISION = 1000_000L; diff --git a/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java b/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java index ab147f57a79..013ba606e9a 100644 --- a/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java +++ b/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java @@ -1,6 +1,8 @@ package org.tron.common.runtime; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.same; import java.lang.reflect.Field; import java.util.Collections; @@ -13,19 +15,70 @@ import org.tron.common.runtime.vm.LogInfo; import org.tron.core.actuator.VMActuator; import org.tron.core.db.TransactionContext; +import org.tron.core.vm.JumpTable; import org.tron.core.vm.OperationRegistry; import org.tron.core.vm.VM; import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program; +import org.tron.core.vm.repository.Repository; public class VMActuatorMockTest { @BeforeClass public static void init() { - // warm up the registry so VM.play(..., OperationRegistry.getTable()) arg eval is safe + // Warm up the registry before VM execution timing starts. OperationRegistry.init(); } + @Test + public void constantCallUsesDedicatedJumpTable() throws Exception { + try (MockedStatic vmMock = Mockito.mockStatic(VM.class)) { + Program program = Mockito.mock(Program.class); + Mockito.when(program.getResult()).thenReturn(new ProgramResult()); + + VMActuator actuator = new VMActuator(true); + Field f = VMActuator.class.getDeclaredField("program"); + f.setAccessible(true); + f.set(actuator, program); + + TransactionContext context = Mockito.mock(TransactionContext.class); + Mockito.when(context.getProgramResult()).thenReturn(new ProgramResult()); + + actuator.execute(context); + + JumpTable transactionTable = OperationRegistry.getTable(false); + JumpTable constantCallTable = OperationRegistry.getTable(true); + vmMock.verify(() -> VM.play(any(), same(constantCallTable))); + vmMock.verify(() -> VM.play(any(), argThat(table -> table != transactionTable))); + } + } + + @Test + public void nonConstantCallUsesSharedJumpTable() throws Exception { + try (MockedStatic vmMock = Mockito.mockStatic(VM.class)) { + Program program = Mockito.mock(Program.class); + Mockito.when(program.getResult()).thenReturn(new ProgramResult()); + + VMActuator actuator = new VMActuator(false); + Field f = VMActuator.class.getDeclaredField("program"); + f.setAccessible(true); + f.set(actuator, program); + + Field repositoryField = VMActuator.class.getDeclaredField("rootRepository"); + repositoryField.setAccessible(true); + repositoryField.set(actuator, Mockito.mock(Repository.class)); + + TransactionContext context = Mockito.mock(TransactionContext.class); + Mockito.when(context.getProgramResult()).thenReturn(new ProgramResult()); + + actuator.execute(context); + + // The non-constant call must receive the shared consensus table itself. + JumpTable shared = OperationRegistry.getTable(false); + vmMock.verify(() -> VM.play(any(), same(shared))); + } + } + private void runCatchPathTest(Throwable thrownByVm, boolean osakaOn, int expectedSize) throws Exception { boolean prevOsaka = VMConfig.allowTvmOsaka(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java index a1627f4f2e2..d6c344263dd 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java @@ -3,6 +3,7 @@ import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; +import static org.tron.core.config.Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2; import java.util.List; import java.util.Locale; @@ -16,6 +17,7 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; @@ -24,6 +26,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.InternalTransaction; import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.ForkController; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -42,6 +45,7 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.Program.OutOfTimeException; import org.tron.core.vm.program.invoke.ProgramInvokeMockImpl; import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; @@ -51,7 +55,7 @@ public class OperationsTest extends BaseTest { private ProgramInvokeMockImpl invoke; private Program program; - private final JumpTable jumpTable = OperationRegistry.getTable(); + private final JumpTable jumpTable = OperationRegistry.prepareAndGetTable(false); @Autowired private Wallet wallet; @@ -1182,6 +1186,7 @@ public void testSuicideAction() throws ContractValidateException { program.suicide(new DataWord( dbManager.getAccountStore().getBlackhole().getAddress().toByteArray())); + Assert.assertTrue(program.getContractState().isSelfDestructed(program.getContextAddress())); DecodeUtil.addressPreFixByte = prePrefixByte; VMConfig.initAllowEnergyAdjustment(0); @@ -1240,6 +1245,7 @@ public void testSuicideAction2() throws ContractValidateException { OperationActions.suicideAction2(program); Assert.assertEquals(1, program.getResult().getDeleteAccounts().size()); + Assert.assertTrue(program.getContractState().isSelfDestructed(contractAddr)); invoke = new ProgramInvokeMockImpl(StoreFactory.getInstance(), new byte[0], contractAddr); @@ -1256,6 +1262,7 @@ public void testSuicideAction2() throws ContractValidateException { dbManager.getAccountStore().getBlackhole().getAddress().toByteArray())); Assert.assertEquals(0, spyProgram.getResult().getDeleteAccounts().size()); + Assert.assertTrue(spyProgram.getContractState().isSelfDestructed(contractAddr)); DecodeUtil.addressPreFixByte = prePrefixByte; VMConfig.initAllowEnergyAdjustment(0); @@ -1266,6 +1273,31 @@ public void testSuicideAction2() throws ContractValidateException { VMConfig.initAllowTvmVote(0); } + @Test + public void testSuicide2RejectsSelfDestructedBeneficiaryAfterFork() + throws ContractValidateException { + byte[] contractAddr = Hex.decode("41471fd3ad3e9eeadeec4608b92d16ce6b500704cc"); + byte[] beneficiary = Hex.decode("411111111111111111111111111111111111111111"); + invoke = new ProgramInvokeMockImpl(StoreFactory.getInstance(), new byte[0], contractAddr); + program = new Program(null, null, invoke, + new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); + program.getContractState().markSelfDestruct(beneficiary); + + ForkController forkController = Mockito.mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + Mockito.when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, + () -> program.suicide2(new DataWord(beneficiary))); + Assert.assertEquals( + "CPU timeout for SELFDESTRUCT with selfdestructed beneficiary", + exception.getMessage()); + } + } + @Test public void testVoteWitnessCost() throws ContractValidateException { // Build stack environment, the stack from top to bottom is 0x00, 0x80, 0x00, 0x80 diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java index 2c7aa238033..b949cbd8dc8 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java @@ -217,7 +217,7 @@ public void testWitnessArrayLargerThanAmountArray() { @Test public void testOperationRegistryWithoutOsaka() { VMConfig.initAllowTvmOsaka(0); - JumpTable table = OperationRegistry.getTable(); + JumpTable table = OperationRegistry.prepareAndGetTable(false); Operation voteOp = table.get(Op.VOTEWITNESS); assertTrue(voteOp.isEnabled()); @@ -233,7 +233,7 @@ public void testOperationRegistryWithoutOsaka() { public void testOperationRegistryWithOsaka() { VMConfig.initAllowTvmOsaka(1); try { - JumpTable table = OperationRegistry.getTable(); + JumpTable table = OperationRegistry.prepareAndGetTable(false); Operation voteOp = table.get(Op.VOTEWITNESS); assertTrue(voteOp.isEnabled()); diff --git a/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java b/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java new file mode 100644 index 00000000000..a2dd0a51e4e --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java @@ -0,0 +1,67 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.ForkController; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; + +public class ContractHashValidationTest { + + @Test + public void acceptsHashFieldsBeforeActivation() { + SmartContract contract = SmartContract.newBuilder() + .setCodeHash(ByteString.copyFromUtf8("code")) + .setTrxHash(ByteString.copyFromUtf8("transaction")) + .build(); + + runWithActivation(false, () -> VMActuator.checkContractHashFields(contract)); + } + + @Test + public void rejectsCodeHashAfterActivation() { + SmartContract contract = SmartContract.newBuilder() + .setCodeHash(ByteString.copyFromUtf8("code")) + .build(); + + OutOfTimeException exception = assertThrows(OutOfTimeException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractHashFields(contract))); + + assertEquals("CPU timeout for contract hash fields", exception.getMessage()); + } + + @Test + public void rejectsTransactionHashAfterActivation() { + SmartContract contract = SmartContract.newBuilder() + .setTrxHash(ByteString.copyFromUtf8("transaction")) + .build(); + + OutOfTimeException exception = assertThrows(OutOfTimeException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractHashFields(contract))); + + assertEquals("CPU timeout for contract hash fields", exception.getMessage()); + } + + @Test + public void acceptsEmptyHashFieldsAfterActivation() { + runWithActivation(true, + () -> VMActuator.checkContractHashFields(SmartContract.getDefaultInstance())); + } + + private void runWithActivation(boolean activated, Runnable action) { + ForkController controller = mock(ForkController.class); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_2)).thenReturn(activated); + try (MockedStatic controllerMock = Mockito.mockStatic(ForkController.class)) { + controllerMock.when(ForkController::instance).thenReturn(controller); + action.run(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java b/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java new file mode 100644 index 00000000000..e172829e7d6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java @@ -0,0 +1,65 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.ForkController; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; + +public class ContractNameValidationTest { + + @Test + public void acceptsThirtyTwoByteNameAfterActivation() throws Throwable { + SmartContract contract = contractWithName("12345678901234567890123456789012"); + + runWithActivation(true, () -> VMActuator.checkContractNameLength(contract)); + } + + @Test + public void rejectsThirtyThreeByteNameAfterActivation() { + SmartContract contract = contractWithName("123456789012345678901234567890123"); + + ContractValidateException exception = assertThrows(ContractValidateException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractNameLength(contract))); + + assertEquals("contractName's length cannot be greater than 32", exception.getMessage()); + } + + @Test + public void countsMultibyteNameUsingProtobufBytesAfterActivation() { + SmartContract contract = contractWithName("合合合合合合合合合合合"); + assertEquals(33, contract.getNameBytes().size()); + + assertThrows(ContractValidateException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractNameLength(contract))); + } + + @Test + public void preservesNameValidationBeforeActivation() { + SmartContract contract = contractWithName("123456789012345678901234567890123"); + + assertThrows(ContractValidateException.class, + () -> runWithActivation(false, () -> VMActuator.checkContractNameLength(contract))); + } + + private SmartContract contractWithName(String name) { + return SmartContract.newBuilder().setName(name).build(); + } + + private void runWithActivation(boolean activated, ThrowingRunnable action) throws Throwable { + ForkController controller = mock(ForkController.class); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_2)).thenReturn(activated); + try (MockedStatic controllerMock = Mockito.mockStatic(ForkController.class)) { + controllerMock.when(ForkController::instance).thenReturn(controller); + action.run(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java b/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java new file mode 100644 index 00000000000..b6568f8a862 --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java @@ -0,0 +1,142 @@ +package org.tron.core.vm; + +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import org.junit.Test; +import org.tron.core.vm.config.VMConfig; + +public class OperationRegistryTest { + + @Test + public void constantAndTransactionExecutionsUseDedicatedTables() { + JumpTable transactionTable = OperationRegistry.prepareAndGetTable(false); + JumpTable constantCallTable = OperationRegistry.prepareAndGetTable(true); + + assertNotSame(transactionTable, constantCallTable); + assertSame(transactionTable, OperationRegistry.getTable(false)); + assertSame(constantCallTable, OperationRegistry.getTable(true)); + } + + @Test + public void transactionExecutionsReuseTable() { + JumpTable first = OperationRegistry.prepareAndGetTable(false); + JumpTable second = OperationRegistry.prepareAndGetTable(false); + + assertSame(first, second); + } + + @Test + public void constantExecutionsReuseTable() { + JumpTable first = OperationRegistry.prepareAndGetTable(true); + JumpTable second = OperationRegistry.prepareAndGetTable(true); + + assertSame(first, second); + } + + @Test + public void constantAdjustmentsDoNotMutateTransactionTable() { + boolean previousHigherLimit = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + JumpTable transactionTable = OperationRegistry.getTable(false); + JumpTable constantCallTable = OperationRegistry.getTable(true); + try { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(0); + OperationRegistry.adjustMemOperations(transactionTable); + OperationRegistry.adjustMemOperations(constantCallTable); + Operation transactionMload = transactionTable.get(Op.MLOAD); + Operation constantMload = constantCallTable.get(Op.MLOAD); + + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(1); + OperationRegistry.adjustMemOperations(constantCallTable); + + assertSame(transactionMload, transactionTable.get(Op.MLOAD)); + assertNotSame(constantMload, constantCallTable.get(Op.MLOAD)); + } finally { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(previousHigherLimit ? 1 : 0); + OperationRegistry.adjustMemOperations(transactionTable); + OperationRegistry.adjustMemOperations(constantCallTable); + } + } + + @Test + public void adjustedOperationsReuseCachedVariants() { + boolean previousHigherLimit = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + boolean previousEnergyAdjustment = VMConfig.allowEnergyAdjustment(); + boolean previousOsaka = VMConfig.allowTvmOsaka(); + boolean previousSelfdestructRestriction = VMConfig.allowTvmSelfdestructRestriction(); + JumpTable table = OperationRegistry.newTronV15OperationSet(); + + Operation defaultMload = table.get(Op.MLOAD); + Operation defaultMstore = table.get(Op.MSTORE); + Operation defaultMstore8 = table.get(Op.MSTORE8); + Operation defaultVoteWitness = table.get(Op.VOTEWITNESS); + Operation defaultSuicide = table.get(Op.SUICIDE); + + try { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(1); + VMConfig.initAllowEnergyAdjustment(1); + VMConfig.initAllowTvmOsaka(0); + VMConfig.initAllowTvmSelfdestructRestriction(0); + adjustOperations(table); + + Operation adjustedMload = table.get(Op.MLOAD); + Operation adjustedMstore = table.get(Op.MSTORE); + Operation adjustedMstore8 = table.get(Op.MSTORE8); + Operation adjustedVoteWitness = table.get(Op.VOTEWITNESS); + Operation adjustedSuicide = table.get(Op.SUICIDE); + + assertNotSame(defaultMload, adjustedMload); + assertNotSame(defaultMstore, adjustedMstore); + assertNotSame(defaultMstore8, adjustedMstore8); + assertNotSame(defaultVoteWitness, adjustedVoteWitness); + assertNotSame(defaultSuicide, adjustedSuicide); + + adjustOperations(table); + assertSame(adjustedMload, table.get(Op.MLOAD)); + assertSame(adjustedMstore, table.get(Op.MSTORE)); + assertSame(adjustedMstore8, table.get(Op.MSTORE8)); + assertSame(adjustedVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(adjustedSuicide, table.get(Op.SUICIDE)); + + VMConfig.initAllowTvmOsaka(1); + VMConfig.initAllowTvmSelfdestructRestriction(1); + adjustOperations(table); + + Operation osakaVoteWitness = table.get(Op.VOTEWITNESS); + Operation restrictedSuicide = table.get(Op.SUICIDE); + assertNotSame(adjustedVoteWitness, osakaVoteWitness); + assertNotSame(adjustedSuicide, restrictedSuicide); + + adjustOperations(table); + assertSame(adjustedMload, table.get(Op.MLOAD)); + assertSame(adjustedMstore, table.get(Op.MSTORE)); + assertSame(adjustedMstore8, table.get(Op.MSTORE8)); + assertSame(osakaVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(restrictedSuicide, table.get(Op.SUICIDE)); + + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(0); + VMConfig.initAllowEnergyAdjustment(0); + VMConfig.initAllowTvmOsaka(0); + VMConfig.initAllowTvmSelfdestructRestriction(0); + adjustOperations(table); + + assertSame(defaultMload, table.get(Op.MLOAD)); + assertSame(defaultMstore, table.get(Op.MSTORE)); + assertSame(defaultMstore8, table.get(Op.MSTORE8)); + assertSame(defaultVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(defaultSuicide, table.get(Op.SUICIDE)); + } finally { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(previousHigherLimit ? 1 : 0); + VMConfig.initAllowEnergyAdjustment(previousEnergyAdjustment ? 1 : 0); + VMConfig.initAllowTvmOsaka(previousOsaka ? 1 : 0); + VMConfig.initAllowTvmSelfdestructRestriction( + previousSelfdestructRestriction ? 1 : 0); + } + } + + private static void adjustOperations(JumpTable table) { + OperationRegistry.adjustMemOperations(table); + OperationRegistry.adjustVoteWitness(table); + OperationRegistry.adjustSelfdestruct(table); + } +} diff --git a/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java b/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java new file mode 100644 index 00000000000..a3c59019b6d --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java @@ -0,0 +1,186 @@ +package org.tron.core.vm.nativecontract; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.config.Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; +import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; +import org.tron.core.vm.nativecontract.param.UnfreezeBalanceV2Param; +import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; +import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; +import org.tron.protos.contract.Common.ResourceCode; + +public class StakeV2AfterSelfDestructTest { + + private static final long NOW = 1_000L; + + @Test + public void freezeAfterSelfDestructIsForkGated() throws Exception { + byte[] ownerAddress = address(1); + AccountCapsule owner = account(ownerAddress, 0, 0); + owner.setBalance(TRX_PRECISION); + + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(repository.getAccount(ownerAddress)).thenReturn(owner); + when(repository.isSelfDestructed(ownerAddress)).thenReturn(true); + + FreezeBalanceV2Param param = new FreezeBalanceV2Param(); + param.setOwnerAddress(ownerAddress); + param.setFrozenBalance(TRX_PRECISION); + param.setResourceType(BANDWIDTH); + FreezeBalanceV2Processor processor = new FreezeBalanceV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + processor.validate(param, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + assertFreezeV2Timeout(() -> processor.validate(param, repository)); + } + } + + @Test + public void invalidDelegatedBalancesBlockWithdrawAndCancelAfterFork() throws Exception { + byte[] ownerAddress = address(1); + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(dynamicStore.getLatestBlockHeaderTimestamp()).thenReturn(NOW); + + WithdrawExpireUnfreezeParam withdrawParam = new WithdrawExpireUnfreezeParam(); + withdrawParam.setOwnerAddress(ownerAddress); + WithdrawExpireUnfreezeProcessor withdrawProcessor = + new WithdrawExpireUnfreezeProcessor(); + CancelAllUnfreezeV2Param cancelParam = new CancelAllUnfreezeV2Param(); + cancelParam.setOwnerAddress(ownerAddress); + CancelAllUnfreezeV2Processor cancelProcessor = new CancelAllUnfreezeV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, -1, 0)); + withdrawProcessor.validate(withdrawParam, repository); + cancelProcessor.validate(cancelParam, repository); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, 0, -1)); + withdrawProcessor.validate(withdrawParam, repository); + cancelProcessor.validate(cancelParam, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, -1, 0)); + assertInvalidDelegatedV2Timeout( + () -> withdrawProcessor.validate(withdrawParam, repository)); + assertInvalidDelegatedV2Timeout( + () -> cancelProcessor.validate(cancelParam, repository)); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, 0, -1)); + assertInvalidDelegatedV2Timeout( + () -> withdrawProcessor.validate(withdrawParam, repository)); + assertInvalidDelegatedV2Timeout( + () -> cancelProcessor.validate(cancelParam, repository)); + } + } + + @Test + public void invalidDelegatedBalancesBlockUnfreezeAfterFork() throws Exception { + byte[] ownerAddress = address(1); + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(dynamicStore.getLatestBlockHeaderTimestamp()).thenReturn(NOW); + + UnfreezeBalanceV2Param bandwidthParam = unfreezeParam(ownerAddress, BANDWIDTH); + UnfreezeBalanceV2Param energyParam = unfreezeParam(ownerAddress, ENERGY); + UnfreezeBalanceV2Processor processor = new UnfreezeBalanceV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, -1, 0, BANDWIDTH)); + processor.validate(bandwidthParam, repository); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, 0, -1, ENERGY)); + processor.validate(energyParam, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, -1, 0, BANDWIDTH)); + assertInvalidDelegatedV2Timeout( + () -> processor.validate(bandwidthParam, repository)); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, 0, -1, ENERGY)); + assertInvalidDelegatedV2Timeout(() -> processor.validate(energyParam, repository)); + } + } + + private static AccountCapsule account(byte[] address, long bandwidth, long energy) { + Protocol.Account.AccountResource resource = Protocol.Account.AccountResource.newBuilder() + .setDelegatedFrozenV2BalanceForEnergy(energy) + .build(); + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .setDelegatedFrozenV2BalanceForBandwidth(bandwidth) + .setAccountResource(resource) + .build(); + return new AccountCapsule(account); + } + + private static AccountCapsule accountWithFrozenV2( + byte[] address, long bandwidth, long energy, ResourceCode resourceCode) { + AccountCapsule accountCapsule = account(address, bandwidth, energy); + if (resourceCode == BANDWIDTH) { + accountCapsule.addFrozenBalanceForBandwidthV2(TRX_PRECISION); + } else { + accountCapsule.addFrozenBalanceForEnergyV2(TRX_PRECISION); + } + return accountCapsule; + } + + private static UnfreezeBalanceV2Param unfreezeParam( + byte[] ownerAddress, ResourceCode resourceCode) { + UnfreezeBalanceV2Param param = new UnfreezeBalanceV2Param(); + param.setOwnerAddress(ownerAddress); + param.setResourceType(resourceCode); + param.setUnfreezeBalance(TRX_PRECISION); + return param; + } + + private static byte[] address(int suffix) { + byte[] address = new byte[21]; + address[0] = DecodeUtil.addressPreFixByte; + address[address.length - 1] = (byte) suffix; + return address; + } + + private static void assertFreezeV2Timeout(ThrowingRunnable runnable) { + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, runnable); + Assert.assertEquals( + "CPU timeout for FreezeBalanceV2 after SELFDESTRUCT", exception.getMessage()); + } + + private static void assertInvalidDelegatedV2Timeout(ThrowingRunnable runnable) { + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, runnable); + Assert.assertEquals("CPU timeout for invalid delegated V2 balance", exception.getMessage()); + } +} diff --git a/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java b/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java new file mode 100644 index 00000000000..10131a06595 --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java @@ -0,0 +1,36 @@ +package org.tron.core.vm.repository; + +import org.junit.Assert; +import org.junit.Test; + +public class RepositoryImplSelfDestructTest { + + private static final byte[] ADDRESS = new byte[] {1}; + + @Test + public void committedSelfDestructMarkerIsVisibleToParentAndSibling() { + Repository root = RepositoryImpl.createRoot(null); + Repository child = root.newRepositoryChild(); + + child.markSelfDestruct(ADDRESS); + Assert.assertTrue(child.isSelfDestructed(ADDRESS)); + Assert.assertFalse(root.isSelfDestructed(ADDRESS)); + + child.commit(); + Assert.assertTrue(root.isSelfDestructed(ADDRESS)); + Assert.assertTrue(root.newRepositoryChild().isSelfDestructed(ADDRESS)); + } + + @Test + public void nestedMarkerDoesNotLeakWhenOuterCallIsReverted() { + Repository root = RepositoryImpl.createRoot(null); + Repository outerCall = root.newRepositoryChild(); + Repository nestedCall = outerCall.newRepositoryChild(); + + nestedCall.markSelfDestruct(ADDRESS); + nestedCall.commit(); + + Assert.assertTrue(outerCall.isSelfDestructed(ADDRESS)); + Assert.assertFalse(root.isSelfDestructed(ADDRESS)); + } +} From d5c3d1d1fd0cad12f09c4346d6ac937ab2cbb071 Mon Sep 17 00:00:00 2001 From: Asuka Date: Tue, 8 Sep 2026 20:43:42 +0800 Subject: [PATCH 4/8] update a new version. version name:GreatVoyage-v4.8.2.1-1-gbd2450fe06,version code:18828 (#6955) --- framework/src/main/java/org/tron/program/Version.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index f34d440702e..64f2befa2ef 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -2,9 +2,9 @@ public class Version { - public static final String VERSION_NAME = "GreatVoyage-v4.8.2-6-g348db25bfd"; - public static final String VERSION_CODE = "18825"; - private static final String VERSION = "4.8.2.1"; + public static final String VERSION_NAME = "GreatVoyage-v4.8.2.1-1-gbd2450fe06"; + public static final String VERSION_CODE = "18828"; + private static final String VERSION = "4.8.2.2"; public static String getVersion() { return VERSION; From b33eed89a6a424c498d4fb1b03ca2c86eddf4840 Mon Sep 17 00:00:00 2001 From: xxo1_shine Date: Fri, 11 Sep 2026 14:15:03 +0800 Subject: [PATCH 5/8] fix(api): correct node info and network metric mappings (#6930) Node and network API responses populated two fields from the wrong source values because of copy-and-paste mapping errors. Map needSyncFromPeer from the corresponding peer state and assign UDP inbound traffic to the udpInTraffic protobuf field. --- .../java/org/tron/common/entity/NodeInfo.java | 2 +- .../org/tron/common/entity/NodeInfoTest.java | 58 +++++++++++++++++++ .../core/metrics/net/NetMetricManager.java | 2 +- .../core/metrics/MetricsApiServiceTest.java | 18 ++++++ 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 common/src/test/java/org/tron/common/entity/NodeInfoTest.java diff --git a/common/src/main/java/org/tron/common/entity/NodeInfo.java b/common/src/main/java/org/tron/common/entity/NodeInfo.java index 4b23bd185e3..6f53b3935b8 100644 --- a/common/src/main/java/org/tron/common/entity/NodeInfo.java +++ b/common/src/main/java/org/tron/common/entity/NodeInfo.java @@ -146,7 +146,7 @@ public Protocol.NodeInfo transferToProtoEntity() { peerInfoBuilder.setLastBlockUpdateTime(peerInfo.getLastBlockUpdateTime()); peerInfoBuilder.setSyncFlag(peerInfo.isSyncFlag()); peerInfoBuilder.setHeadBlockTimeWeBothHave(peerInfo.getHeadBlockTimeWeBothHave()); - peerInfoBuilder.setNeedSyncFromPeer(peerInfo.isSyncFlag()); + peerInfoBuilder.setNeedSyncFromPeer(peerInfo.isNeedSyncFromPeer()); peerInfoBuilder.setNeedSyncFromUs(peerInfo.isNeedSyncFromUs()); peerInfoBuilder.setHost(peerInfo.getHost()); peerInfoBuilder.setPort(peerInfo.getPort()); diff --git a/common/src/test/java/org/tron/common/entity/NodeInfoTest.java b/common/src/test/java/org/tron/common/entity/NodeInfoTest.java new file mode 100644 index 00000000000..302fdb7b080 --- /dev/null +++ b/common/src/test/java/org/tron/common/entity/NodeInfoTest.java @@ -0,0 +1,58 @@ +package org.tron.common.entity; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.tron.protos.Protocol; + +public class NodeInfoTest { + + private PeerInfo newPeerInfo(boolean syncFlag, boolean needSyncFromPeer, + boolean needSyncFromUs) { + PeerInfo peerInfo = new PeerInfo(); + peerInfo.setSyncFlag(syncFlag); + peerInfo.setNeedSyncFromPeer(needSyncFromPeer); + peerInfo.setNeedSyncFromUs(needSyncFromUs); + // string fields must be non-null, otherwise the protobuf setters throw NPE + peerInfo.setLastSyncBlock(""); + peerInfo.setHost("127.0.0.1"); + peerInfo.setNodeId(""); + peerInfo.setHeadBlockWeBothHave(""); + peerInfo.setLocalDisconnectReason(""); + peerInfo.setRemoteDisconnectReason(""); + return peerInfo; + } + + /** + * The protobuf conversion must map each peer flag from its own source field. A previous + * copy-and-paste defect populated needSyncFromPeer from isSyncFlag(); distinct values for + * syncFlag and needSyncFromPeer are required so that such a mismatch is detected. + */ + @Test + public void testPeerFlagMappingIsIndependent() { + NodeInfo nodeInfo = new NodeInfo(); + nodeInfo.setBlock(""); + nodeInfo.setSolidityBlock(""); + List peerList = new ArrayList<>(); + // syncFlag != needSyncFromPeer so the two fields cannot be confused + peerList.add(newPeerInfo(false, true, false)); + peerList.add(newPeerInfo(true, false, true)); + nodeInfo.setPeerList(peerList); + nodeInfo.setCheatWitnessInfoMap(new java.util.HashMap<>()); + + Protocol.NodeInfo proto = nodeInfo.transferToProtoEntity(); + + Assert.assertEquals(2, proto.getPeerInfoListCount()); + + Protocol.NodeInfo.PeerInfo peer0 = proto.getPeerInfoList(0); + Assert.assertFalse(peer0.getSyncFlag()); + Assert.assertTrue(peer0.getNeedSyncFromPeer()); + Assert.assertFalse(peer0.getNeedSyncFromUs()); + + Protocol.NodeInfo.PeerInfo peer1 = proto.getPeerInfoList(1); + Assert.assertTrue(peer1.getSyncFlag()); + Assert.assertFalse(peer1.getNeedSyncFromPeer()); + Assert.assertTrue(peer1.getNeedSyncFromUs()); + } +} diff --git a/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java b/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java index 38dfccff05a..037580037e3 100644 --- a/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java +++ b/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java @@ -181,7 +181,7 @@ public Protocol.MetricsInfo.NetInfo getNetProtoInfo() { // udp RateInfo udpInTraffic = net.getUdpInTraffic(); Protocol.MetricsInfo.RateInfo udpInTrafficInfo = udpInTraffic.toProtoEntity(); - netInfo.setTcpOutTraffic(udpInTrafficInfo); + netInfo.setUdpInTraffic(udpInTrafficInfo); RateInfo udpOutTraffic = net.getUdpOutTraffic(); Protocol.MetricsInfo.RateInfo udpOutTrafficInfo = udpOutTraffic.toProtoEntity(); netInfo.setUdpOutTraffic(udpOutTrafficInfo); diff --git a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java index f96a03d92e3..07f7bcfc6e8 100644 --- a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java @@ -38,6 +38,10 @@ protected void afterInit() { @Test public void testProcessMessage() { + MetricsUtil.getMeter(MetricsKey.NET_TCP_IN_TRAFFIC).mark(1000); + MetricsUtil.getMeter(MetricsKey.NET_TCP_OUT_TRAFFIC).mark(2000); + MetricsUtil.getMeter(MetricsKey.NET_UDP_IN_TRAFFIC).mark(4000); + MetricsUtil.getMeter(MetricsKey.NET_UDP_OUT_TRAFFIC).mark(8000); MetricsInfo m1 = metricsApiService.getMetricsInfo(); @@ -79,6 +83,20 @@ public void testProcessMessage() { Assert.assertEquals(m1.getNet().getErrorProtoCount(), m2.getNet().getErrorProtoCount()); Assert .assertEquals(m1.getNet().getValidConnectionCount(), m2.getNet().getValidConnectionCount()); + + long tcpIn = m1.getNet().getTcpInTraffic().getCount(); + long tcpOut = m1.getNet().getTcpOutTraffic().getCount(); + long udpIn = m1.getNet().getUdpInTraffic().getCount(); + long udpOut = m1.getNet().getUdpOutTraffic().getCount(); + + Assert.assertNotEquals(tcpOut, udpIn); + Assert.assertNotEquals(tcpIn, tcpOut); + Assert.assertNotEquals(udpIn, udpOut); + + Assert.assertEquals(tcpIn, m2.getNet().getTcpInTraffic().getCount()); + Assert.assertEquals(tcpOut, m2.getNet().getTcpOutTraffic().getCount()); + Assert.assertEquals(udpIn, m2.getNet().getUdpInTraffic().getCount()); + Assert.assertEquals(udpOut, m2.getNet().getUdpOutTraffic().getCount()); } } From a219222bbd019d9787a90ce8791000e1c2b76117 Mon Sep 17 00:00:00 2001 From: halibobo1205 <82020050+halibobo1205@users.noreply.github.com> Date: Mon, 14 Sep 2026 14:41:49 +0800 Subject: [PATCH 6/8] chore(deps): upgrade grpc, jackson, logback, commons and drop joda-time (#6950) * chore(deps): upgrade grpc-java from 1.83.0 to 1.83.1 1. bump grpcVersion to 1.83.1 to pick up the upstream fix for grpc/grpc-java#12930 (PR grpc/grpc-java#12942), which enforces connection.remote().maxActiveStreams(maxStreams) at handler startup 2. drop GrpcNettyMaxConcurrentStreamsLimiter, the local protocol-negotiator shim that applied the same limit while 1.83.0 left the remote endpoint unbounded until the client acknowledged SETTINGS * chore(deps): upgrade jackson from 2.18.6 to 2.18.10 bump jackson-databind from 2.18.6 to 2.18.10 to pick up cumulative fixes from the 2.18.x line * chore(deps): upgrade logback to 1.3.16 and slf4j to 2.0.17 1. bump logback-classic from 1.2.13 to 1.3.16 and slf4j-api, jcl-over-slf4j, jul-to-slf4j from 1.7.36 to 2.0.17; logback 1.3 requires the slf4j 2.0 provider model, and 1.3.16 is the last 1.3.x release and the ceiling for the x86_64 JDK 8 build, since 1.5.x requires JDK 11 2. rename DelayingShutdownHook to DefaultShutdownHook in the toolkit logback.xml; logback 1.3 removed the old class and only auto-maps the legacy name with a startup warning 3. drop the CONSOLE appender from the toolkit logback.xml; no logger ever referenced it, so it never emitted output on 1.2 either, and logback 1.3 now flags it with an unreferenced-appender warning 4. accept one known 1.3.x behavior change: SizeAndTimeBasedRollingPolicy now throttles its maxFileSize comparison to once per 60s (SimpleInvocationGate) instead of the adaptive ~100-800ms gate of 1.2.13, so under sustained heavy logging a file can overshoot the 500MB cap by up to 60s of writes before the %i rollover fires; time-based rollover and totalSizeCap/maxHistory cleanup are ungated and unaffected 5. note for operators running a custom --log-config file: well-formed 1.2-era configs using standard elements keep working unchanged (jmxConfigurator degrades to an ignored-property warning, the legacy shutdown hook name is auto-mapped), and malformed XML still fails fast via TronError(LOG_LOAD) exactly as on 1.2; however, a config that references an uninstantiable class (e.g. a custom appender missing from the classpath) now aborts the whole appender-ref phase instead of losing just that one appender, so the node starts with no log output while the ERROR statuses are printed to stdout by LogService * chore(deps): upgrade commons-lang3/collections4 and drop commons-math 1. bump commons-lang3 from 3.4 to 3.20.0; the runtime classpath already resolved 3.18.0 through libp2p 2.2.9's transitive requirement, so align the declaration with what actually ships and move past the CVE-2025-48924 range that the nominal 3.4 still sits in 2. bump commons-collections4 from 4.1 to 4.6.0 3. remove commons-math 2.2; no source file imports org.apache.commons.math and nothing else in the dependency graph requests it * chore(deps): remove joda-time and use JDK time APIs 1. drop the joda-time 2.3 dependency. 2. replace the six new DateTime(millis) log-formatting call sites in DynamicPropertiesStore, DposTask and DposService with a new Time.getIsoTimeString helper backed by java.time; its formatter (yyyy-MM-dd'T'HH:mm:ss.SSSXXX in the system zone) reproduces joda's DateTime.toString() output byte for byte where the JDK and joda 2.3 time-zone databases agree (UTC nodes are unaffected); zones whose rules changed after joda's 2013-era tzdb, e.g. Europe/Moscow, now render the corrected offset for the same instant. 3. replace DateTime.now() day arithmetic in four test classes with the java.time equivalent, ZonedDateTime.now().minusDays(n)/plusDays(n) .toInstant().toEpochMilli(), keeping joda's calendar semantics one-to-one, and map plain DateTime.now().getMillis() to System.currentTimeMillis() --- build.gradle | 16 +- .../core/store/DynamicPropertiesStore.java | 6 +- common/build.gradle | 4 +- .../main/java/org/tron/common/utils/Time.java | 12 + .../org/tron/consensus/dpos/DposService.java | 6 +- .../org/tron/consensus/dpos/DposTask.java | 4 +- .../GrpcNettyMaxConcurrentStreamsLimiter.java | 79 ----- .../tron/common/application/RpcService.java | 3 +- ...cNettyMaxConcurrentStreamsLimiterTest.java | 108 ------ .../NettyHttp2HeaderSecurityTest.java | 53 +++ .../common/utils/RandomGeneratorTest.java | 3 +- .../org/tron/core/BandwidthProcessorTest.java | 18 +- .../test/java/org/tron/core/WalletTest.java | 30 +- .../ParticipateAssetIssueActuatorTest.java | 58 ++-- .../TransactionsMsgHandlerTest.java | 4 +- gradle/verification-metadata.xml | 323 ++++++++++-------- plugins/src/main/resources/logback.xml | 11 +- 17 files changed, 324 insertions(+), 414 deletions(-) delete mode 100644 framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java delete mode 100644 framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java create mode 100644 framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java diff --git a/build.gradle b/build.gradle index 65e72c0fb73..04dee79fbae 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { } ext { - grpcVersion = "1.83.0" + grpcVersion = "1.83.1" } allprojects { @@ -91,16 +91,14 @@ subprojects { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.36' - implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.36' - implementation group: 'org.slf4j', name: 'jul-to-slf4j', version: '1.7.36' - implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.13' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.17' + implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: '2.0.17' + implementation group: 'org.slf4j', name: 'jul-to-slf4j', version: '2.0.17' + implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.3.16' implementation "com.google.code.findbugs:jsr305:3.0.0" implementation group: 'org.springframework', name: 'spring-context', version: "${springVersion}" - implementation "org.apache.commons:commons-lang3:3.4" - implementation group: 'org.apache.commons', name: 'commons-math', version: '2.2' - implementation "org.apache.commons:commons-collections4:4.1" - implementation group: 'joda-time', name: 'joda-time', version: '2.3' + implementation "org.apache.commons:commons-lang3:3.20.0" + implementation "org.apache.commons:commons-collections4:4.6.0" implementation group: 'org.bouncycastle', name: 'bcprov-jdk18on', version: '1.84' compileOnly 'org.projectlombok:lombok:1.18.34' diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 0f74f20d379..33bbaa4a362 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -12,13 +12,13 @@ import java.util.stream.IntStream; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Time; import org.tron.core.capsule.BytesCapsule; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.db.TronStoreWithRevoking; @@ -2261,8 +2261,8 @@ public void updateNextMaintenanceTime(long blockTime) { logger.info( "Do update nextMaintenanceTime, currentMaintenanceTime: {}, blockTime: {}, " + "nextMaintenanceTime: {}.", - new DateTime(currentMaintenanceTime), new DateTime(blockTime), - new DateTime(nextMaintenanceTime) + Time.getIsoTimeString(currentMaintenanceTime), Time.getIsoTimeString(blockTime), + Time.getIsoTimeString(nextMaintenanceTime) ); } diff --git a/common/build.gradle b/common/build.gradle index 14d3eb4e637..4b36d067b70 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -8,7 +8,9 @@ sourceCompatibility = 1.8 dependencies { - api group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.18.6' // https://github.com/FasterXML/jackson-databind/issues/3627 + // avoid x.y.z.w micro-patches, they may ship broken Gradle module metadata: + // https://github.com/FasterXML/jackson-databind/issues/3627 + api group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.18.10' api "com.cedarsoftware:java-util:3.2.0" api group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' api group: 'commons-codec', name: 'commons-codec', version: '1.11' diff --git a/common/src/main/java/org/tron/common/utils/Time.java b/common/src/main/java/org/tron/common/utils/Time.java index fdbfcb5f283..15e9d3d4b55 100644 --- a/common/src/main/java/org/tron/common/utils/Time.java +++ b/common/src/main/java/org/tron/common/utils/Time.java @@ -1,9 +1,17 @@ package org.tron.common.utils; import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; public class Time { + // Matches joda-time's DateTime.toString() output, byte for byte: fixed + // 3-digit millis, offset as +08:00, and Z when the system zone is UTC. + private static final DateTimeFormatter ISO_MILLIS_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + public static long getCurrentMillis() { return System.currentTimeMillis(); } @@ -11,4 +19,8 @@ public static long getCurrentMillis() { public static String getTimeString(long time) { return new Timestamp(time).toString(); } + + public static String getIsoTimeString(long time) { + return Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).format(ISO_MILLIS_FORMAT); + } } diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposService.java b/consensus/src/main/java/org/tron/consensus/dpos/DposService.java index 397c9d0835c..0a40ec8e076 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposService.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposService.java @@ -14,12 +14,12 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.common.args.GenesisBlock; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Time; import org.tron.consensus.ConsensusDelegate; import org.tron.consensus.base.BlockHandle; import org.tron.consensus.base.ConsensusInterface; @@ -134,14 +134,14 @@ public boolean validBlock(BlockCapsule blockCapsule) { if (slot == 0 && consensusDelegate.getDynamicPropertiesStore().allowConsensusLogicOptimization()) { logger.warn("ValidBlock failed: slot error, witness: {}, timeStamp: {}", - ByteArray.toHexString(witnessAddress.toByteArray()), new DateTime(timeStamp)); + ByteArray.toHexString(witnessAddress.toByteArray()), Time.getIsoTimeString(timeStamp)); return false; } final ByteString scheduledWitness = dposSlot.getScheduledWitness(slot); if (!scheduledWitness.equals(witnessAddress)) { logger.warn("ValidBlock failed: sWitness: {}, bWitness: {}, bTimeStamp: {}, slot: {}", ByteArray.toHexString(scheduledWitness.toByteArray()), - ByteArray.toHexString(witnessAddress.toByteArray()), new DateTime(timeStamp), slot); + ByteArray.toHexString(witnessAddress.toByteArray()), Time.getIsoTimeString(timeStamp), slot); return false; } diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java index 9e42552c80f..38f5614e571 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java @@ -6,7 +6,6 @@ import java.util.concurrent.ExecutorService; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; @@ -15,6 +14,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Time; import org.tron.consensus.ConsensusDelegate; import org.tron.consensus.base.Param.Miner; import org.tron.consensus.base.State; @@ -123,7 +123,7 @@ private State produceBlock() { BlockHeader.raw raw = blockCapsule.getInstance().getBlockHeader().getRawData(); logger.info("Produce block successfully, num: {}, time: {}, witness: {}, ID:{}, parentID:{}", raw.getNumber(), - new DateTime(raw.getTimestamp()), + Time.getIsoTimeString(raw.getTimestamp()), ByteArray.toHexString(raw.getWitnessAddress().toByteArray()), new Sha256Hash(raw.getNumber(), Sha256Hash.of(CommonParameter .getInstance().isECKeyCryptoEngine(), raw.toByteArray())), diff --git a/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java b/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java deleted file mode 100644 index cdd71ffee3c..00000000000 --- a/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * java-tron is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * java-tron is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with java-tron. If not, see . - */ - -package org.tron.common.application; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import io.grpc.netty.GrpcHttp2ConnectionHandler; -import io.grpc.netty.InternalProtocolNegotiator; -import io.grpc.netty.InternalProtocolNegotiators; -import io.grpc.netty.NettyServerBuilder; -import io.netty.channel.ChannelHandler; -import io.netty.util.AsciiString; - -/** Enforces the advertised HTTP/2 concurrent stream limit for grpc-netty servers. */ -final class GrpcNettyMaxConcurrentStreamsLimiter { - - private GrpcNettyMaxConcurrentStreamsLimiter() { - } - - static NettyServerBuilder configurePlaintext( - NettyServerBuilder builder, int maxConcurrentStreams) { - checkNotNull(builder, "builder"); - checkArgument(maxConcurrentStreams > 0, "maxConcurrentStreams must be positive"); - builder.maxConcurrentCallsPerConnection(maxConcurrentStreams); - // TODO: Remove this shim after https://github.com/grpc/grpc-java/issues/12930 is fixed. - return builder.protocolNegotiator(newPlaintextNegotiator(maxConcurrentStreams)); - } - - static InternalProtocolNegotiator.ProtocolNegotiator newPlaintextNegotiator( - int maxConcurrentStreams) { - checkArgument(maxConcurrentStreams > 0, "maxConcurrentStreams must be positive"); - return new EnforcingProtocolNegotiator( - InternalProtocolNegotiators.serverPlaintext(), maxConcurrentStreams); - } - - private static final class EnforcingProtocolNegotiator - implements InternalProtocolNegotiator.ProtocolNegotiator { - - private final InternalProtocolNegotiator.ProtocolNegotiator delegate; - private final int maxConcurrentStreams; - - private EnforcingProtocolNegotiator( - InternalProtocolNegotiator.ProtocolNegotiator delegate, int maxConcurrentStreams) { - this.delegate = checkNotNull(delegate, "delegate"); - this.maxConcurrentStreams = maxConcurrentStreams; - } - - @Override - public AsciiString scheme() { - return delegate.scheme(); - } - - @Override - public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { - // grpc-java builds the connection directly, bypassing Netty's builder-side enforcement. - grpcHandler.connection().remote().maxActiveStreams(maxConcurrentStreams); - return delegate.newHandler(grpcHandler); - } - - @Override - public void close() { - delegate.close(); - } - } -} diff --git a/framework/src/main/java/org/tron/common/application/RpcService.java b/framework/src/main/java/org/tron/common/application/RpcService.java index 27fcc479f4e..c398b71ae41 100644 --- a/framework/src/main/java/org/tron/common/application/RpcService.java +++ b/framework/src/main/java/org/tron/common/application/RpcService.java @@ -100,9 +100,8 @@ protected NettyServerBuilder initServerBuilder() { serverBuilder = serverBuilder.executor(this.executorService); } // Set configs from config.conf or default value - serverBuilder = GrpcNettyMaxConcurrentStreamsLimiter.configurePlaintext( - serverBuilder, parameter.getMaxConcurrentCallsPerConnection()); serverBuilder + .maxConcurrentCallsPerConnection(parameter.getMaxConcurrentCallsPerConnection()) .flowControlWindow(parameter.getFlowControlWindow()) .maxConnectionIdle(parameter.getMaxConnectionIdleInMillis(), TimeUnit.MILLISECONDS) .maxConnectionAge(parameter.getMaxConnectionAgeInMillis(), TimeUnit.MILLISECONDS) diff --git a/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java b/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java deleted file mode 100644 index fc578ca7947..00000000000 --- a/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * java-tron is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * java-tron is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with java-tron. If not, see . - */ - -package org.tron.common.application; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; - -import io.grpc.ChannelLogger; -import io.grpc.ChannelLogger.ChannelLogLevel; -import io.grpc.netty.GrpcHttp2ConnectionHandler; -import io.grpc.netty.InternalProtocolNegotiator; -import io.netty.channel.ChannelHandler; -import io.netty.handler.codec.http2.DefaultHttp2Connection; -import io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder; -import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder; -import io.netty.handler.codec.http2.DefaultHttp2FrameReader; -import io.netty.handler.codec.http2.DefaultHttp2FrameWriter; -import io.netty.handler.codec.http2.Http2Connection; -import io.netty.handler.codec.http2.Http2ConnectionDecoder; -import io.netty.handler.codec.http2.Http2ConnectionEncoder; -import io.netty.handler.codec.http2.Http2Error; -import io.netty.handler.codec.http2.Http2Exception; -import io.netty.handler.codec.http2.Http2FrameWriter; -import io.netty.handler.codec.http2.Http2Settings; -import org.junit.Test; - -public class GrpcNettyMaxConcurrentStreamsLimiterTest { - - private static final ChannelLogger NOOP_LOGGER = new ChannelLogger() { - @Override - public void log(ChannelLogLevel level, String message) { - } - - @Override - public void log(ChannelLogLevel level, String messageFormat, Object... args) { - } - }; - - @Test - public void shouldEnforceMaxStreamsBeforeSettingsAck() throws Exception { - Http2Connection connection = new DefaultHttp2Connection(true); - GrpcHttp2ConnectionHandler grpcHandler = newGrpcHandler(connection); - InternalProtocolNegotiator.ProtocolNegotiator negotiator = - GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(2); - - ChannelHandler negotiationHandler = negotiator.newHandler(grpcHandler); - - assertNotNull(negotiationHandler); - assertEquals(2, connection.remote().maxActiveStreams()); - connection.remote().createStream(1, true); - connection.remote().createStream(3, true); - Http2Exception exception = assertThrows( - Http2Exception.class, () -> connection.remote().createStream(5, true)); - assertEquals(Http2Error.REFUSED_STREAM, exception.error()); - negotiator.close(); - } - - @Test - public void shouldIgnoreClientMaxHeaderListSizeOnServer() throws Exception { - Http2Connection connection = new DefaultHttp2Connection(true); - Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); - Http2ConnectionEncoder encoder = - new DefaultHttp2ConnectionEncoder(connection, frameWriter); - long originalMaxHeaderListSize = - encoder.configuration().headersConfiguration().maxHeaderListSize(); - - encoder.remoteSettings(new Http2Settings().maxHeaderListSize(1)); - - assertEquals(originalMaxHeaderListSize, - encoder.configuration().headersConfiguration().maxHeaderListSize()); - encoder.close(); - } - - @Test - public void shouldRejectNonPositiveStreamLimit() { - IllegalArgumentException zeroLimitException = assertThrows(IllegalArgumentException.class, - () -> GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(0)); - assertEquals("maxConcurrentStreams must be positive", zeroLimitException.getMessage()); - IllegalArgumentException negativeLimitException = assertThrows(IllegalArgumentException.class, - () -> GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(-1)); - assertEquals("maxConcurrentStreams must be positive", negativeLimitException.getMessage()); - } - - private static GrpcHttp2ConnectionHandler newGrpcHandler(Http2Connection connection) { - Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); - Http2ConnectionEncoder encoder = - new DefaultHttp2ConnectionEncoder(connection, frameWriter); - Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder( - connection, encoder, new DefaultHttp2FrameReader()); - return new GrpcHttp2ConnectionHandler( - null, decoder, encoder, new Http2Settings(), NOOP_LOGGER) { - }; - } -} diff --git a/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java b/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java new file mode 100644 index 00000000000..6a4f4330f04 --- /dev/null +++ b/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java @@ -0,0 +1,53 @@ +/* + * java-tron is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * java-tron is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with java-tron. If not, see . + */ + +package org.tron.common.application; + +import static org.junit.Assert.assertEquals; + +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder; +import io.netty.handler.codec.http2.DefaultHttp2FrameWriter; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2ConnectionEncoder; +import io.netty.handler.codec.http2.Http2FrameWriter; +import io.netty.handler.codec.http2.Http2Settings; +import org.junit.Test; + +/** Guards the netty HTTP/2 header-size behaviour the gRPC server relies on. */ +public class NettyHttp2HeaderSecurityTest { + + /** + * CVE-2026-50560: SETTINGS_MAX_HEADER_LIST_SIZE tells the server what the client is willing to + * receive, so it must not shrink the server encoder's own limit. Otherwise a hostile client can + * advertise a tiny value and make every response-header write throw, which is a Rapid-Reset-like + * denial of service. Netty enforced the client value before 4.1.135.Final / 4.2.15.Final. + */ + @Test + public void shouldIgnoreClientMaxHeaderListSizeOnServer() throws Exception { + Http2Connection connection = new DefaultHttp2Connection(true); + Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); + Http2ConnectionEncoder encoder = + new DefaultHttp2ConnectionEncoder(connection, frameWriter); + long originalMaxHeaderListSize = + encoder.configuration().headersConfiguration().maxHeaderListSize(); + + encoder.remoteSettings(new Http2Settings().maxHeaderListSize(1)); + + assertEquals(originalMaxHeaderListSize, + encoder.configuration().headersConfiguration().maxHeaderListSize()); + encoder.close(); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java index 4de441d940d..34c7536ebd0 100644 --- a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java +++ b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -42,7 +41,7 @@ public void shuffle() { final List witnessCapsuleListBefore = this.getWitnessList(); logger.info("updateWitnessSchedule,before: " + getWitnessStringList(witnessCapsuleListBefore)); final List witnessCapsuleListAfter = new RandomGenerator() - .shuffle(witnessCapsuleListBefore, DateTime.now().getMillis()); + .shuffle(witnessCapsuleListBefore, System.currentTimeMillis()); logger.info("updateWitnessSchedule,after: " + getWitnessStringList(witnessCapsuleListAfter)); } diff --git a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java index cf652af3650..622d20ae7d2 100755 --- a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java +++ b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java @@ -5,8 +5,8 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import java.nio.charset.StandardCharsets; +import java.time.ZonedDateTime; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -64,8 +64,8 @@ public class BandwidthProcessorTest extends BaseTest { TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; ASSET_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; ASSET_ADDRESS_V2 = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a7890"; - START_TIME = DateTime.now().minusDays(1).getMillis(); - END_TIME = DateTime.now().getMillis(); + START_TIME = ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + END_TIME = System.currentTimeMillis(); } /** @@ -616,7 +616,7 @@ public void sameTokenNameCloseConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -627,7 +627,7 @@ public void sameTokenNameCloseConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().put(toAddressCapsule.getAddress().toByteArray(), toAddressCapsule); @@ -731,7 +731,7 @@ public void sameTokenNameOpenConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -742,7 +742,7 @@ public void sameTokenNameOpenConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().put(toAddressCapsule.getAddress().toByteArray(), toAddressCapsule); @@ -816,7 +816,7 @@ public void sameTokenNameCloseTransferToAccountNotExist() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -827,7 +827,7 @@ public void sameTokenNameCloseTransferToAccountNotExist() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().delete(toAddressCapsule.getAddress().toByteArray()); diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 9dbab338b67..7215a287912 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -30,12 +30,12 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import javax.annotation.Resource; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; @@ -113,21 +113,29 @@ public class WalletTest extends BaseTest { public static final long BLOCK_NUM_THREE = 3; public static final long BLOCK_NUM_FOUR = 4; public static final long BLOCK_NUM_FIVE = 5; - public static final long BLOCK_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); - public static final long BLOCK_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); - public static final long BLOCK_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); - public static final long BLOCK_TIMESTAMP_FOUR = DateTime.now().minusDays(1).getMillis(); - public static final long BLOCK_TIMESTAMP_FIVE = DateTime.now().getMillis(); + public static final long BLOCK_TIMESTAMP_ONE = + ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_TWO = + ZonedDateTime.now().minusDays(3).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_THREE = + ZonedDateTime.now().minusDays(2).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_FOUR = + ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_FIVE = System.currentTimeMillis(); public static final long BLOCK_WITNESS_ONE = 12; public static final long BLOCK_WITNESS_TWO = 13; public static final long BLOCK_WITNESS_THREE = 14; public static final long BLOCK_WITNESS_FOUR = 15; public static final long BLOCK_WITNESS_FIVE = 16; - public static final long TRANSACTION_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); - public static final long TRANSACTION_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); - public static final long TRANSACTION_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); - public static final long TRANSACTION_TIMESTAMP_FOUR = DateTime.now().minusDays(1).getMillis(); - public static final long TRANSACTION_TIMESTAMP_FIVE = DateTime.now().getMillis(); + public static final long TRANSACTION_TIMESTAMP_ONE = + ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_TWO = + ZonedDateTime.now().minusDays(3).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_THREE = + ZonedDateTime.now().minusDays(2).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_FOUR = + ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_FIVE = System.currentTimeMillis(); @Resource private Wallet wallet; private static Block block1; diff --git a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java index 5c168f51bee..4af63285b1e 100755 --- a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java @@ -2,7 +2,7 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import org.joda.time.DateTime; +import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -403,8 +403,8 @@ public void sameTokenNameOpenRightAssetIssue() { */ @Test public void sameTokenNameCloseAssetIssueTimeRight() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -436,8 +436,8 @@ public void sameTokenNameCloseAssetIssueTimeRight() { @Test public void sameTokenNameOpenAssetIssueTimeRight() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -470,8 +470,8 @@ public void sameTokenNameOpenAssetIssueTimeRight() { */ @Test public void sameTokenNameCloseAssetIssueTimeLeft() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -504,8 +504,8 @@ public void sameTokenNameCloseAssetIssueTimeLeft() { @Test public void sameTokenNameOpenAssetIssueTimeLeft() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -605,8 +605,9 @@ public void sameTokenNameOpenExchangeDevisibleTest() { */ @Test public void sameTokenNameCloseNegativeAmountTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(-999L)); @@ -639,8 +640,9 @@ public void sameTokenNameCloseNegativeAmountTest() { @Test public void sameTokenNameOpenNegativeAmountTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(-999L)); @@ -675,8 +677,9 @@ public void sameTokenNameOpenNegativeAmountTest() { */ @Test public void sameTokenNameCloseZeroAmountTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(0)); @@ -709,8 +712,9 @@ public void sameTokenNameCloseZeroAmountTest() { @Test public void sameTokenNameOpenZeroAmountTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(0)); @@ -746,8 +750,9 @@ public void sameTokenNameOpenZeroAmountTest() { */ @Test public void sameTokenNameCloseNoExitOwnerTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContractWithOwner(101, NOT_EXIT_ADDRESS)); @@ -782,8 +787,9 @@ public void sameTokenNameCloseNoExitOwnerTest() { @Test public void sameTokenNameOpenNoExitOwnerTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContractWithOwner(101, NOT_EXIT_ADDRESS)); @@ -1310,8 +1316,9 @@ public void sameTokenNameOpenNotEnoughAssetTest() { */ @Test public void sameTokenNameCloseNoneExistAssetTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContract(1, "TTTTTTTTTTTT")); @@ -1346,8 +1353,9 @@ public void sameTokenNameCloseNoneExistAssetTest() { @Test public void sameTokenNameOpenNoneExistAssetTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContract(1, "TTTTTTTTTTTT")); diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java index ed2121d360f..78af06e64bc 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java @@ -4,6 +4,7 @@ import com.google.protobuf.ByteString; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -14,7 +15,6 @@ import java.util.concurrent.RejectedExecutionException; import lombok.Getter; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -67,7 +67,7 @@ public void testProcessMessage() { .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString("121212a9cf"))) .setToAddress(ByteString.copyFrom(ByteArray.fromHexString("232323a9cf"))).build(); - long transactionTimestamp = DateTime.now().minusDays(4).getMillis(); + long transactionTimestamp = ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); Protocol.Transaction trx = Protocol.Transaction.newBuilder().setRawData( Protocol.Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) .setRefBlockNum(1) diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 6a3e641d5d6..2e30496116f 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -49,25 +49,25 @@ - - - + + + - - + + - - - + + + - - + + - - - + + + @@ -189,9 +189,9 @@ - - - + + + @@ -199,9 +199,9 @@ - - - + + + @@ -219,15 +219,15 @@ - - - + + + - - + + - - + + @@ -235,15 +235,15 @@ - - - + + + - - + + - - + + @@ -251,15 +251,15 @@ - - - + + + - - + + - - + + @@ -1171,76 +1171,76 @@ - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + @@ -1251,18 +1251,18 @@ - - - + + + - - + + - - + + - - + + @@ -1528,14 +1528,6 @@ - - - - - - - - @@ -1684,11 +1676,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1710,36 +1728,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + @@ -1792,6 +1783,11 @@ + + + + + @@ -2408,6 +2404,14 @@ + + + + + + + + @@ -2424,6 +2428,14 @@ + + + + + + + + @@ -2448,6 +2460,11 @@ + + + + + @@ -2612,20 +2629,20 @@ - - - + + + - - + + - - - + + + - - + + @@ -2647,16 +2664,26 @@ - - - - - - + + + + + + + + + + + + + + + + diff --git a/plugins/src/main/resources/logback.xml b/plugins/src/main/resources/logback.xml index fa557f1a412..3f5eff3a1e0 100644 --- a/plugins/src/main/resources/logback.xml +++ b/plugins/src/main/resources/logback.xml @@ -3,16 +3,7 @@ - - - - - %d{HH:mm:ss.SSS} %-5level [%t] [%c{1}]\(%F:%L\) %m%n - - - INFO - - + From 0d1948531818f78a6254d4bd6c11ba7043fae318 Mon Sep 17 00:00:00 2001 From: halibobo1205 <82020050+halibobo1205@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:07:22 +0800 Subject: [PATCH 7/8] feat(api): sanitize HTTP API error responses (#6954) * feat(api): sanitize HTTP API error responses Standard HTTP error paths used to expose internal details to clients: Util.processError prefixed every message with the Java exception class name, several servlets printed raw Throwable.getMessage() directly, and the two solidity query endpoints returned bare-text error bodies. Centralize the client-facing text decision in Util.processError: * keep the raw non-blank message only for the exact runtime types JsonFormat.ParseException, ContractValidateException and MaintenanceUnavailableException; a null, empty or whitespace-only message falls back to "internal server error" * preserve the events-deprecation message only for the exact IllegalArgumentException type carrying EVENTS_DEPRECATED_MSG * write the fixed rate-limit and INVALID address messages, along with existing GetBlock validation messages, through the package-private writeAuditedError helper; these audited callers bypass exception classification, and printErrorMsg is private to the shared writer * return {"Error":"internal server error"} for every other exception, with no exception class name Client-visible changes: * all processError-based error bodies lose the "class : " prefix; unclassified raw messages become "internal server error" * the rate-limit rejection body becomes {"Error":"lack of computing resources"} on every endpoint extending RateLimiterServlet, including full-node, solidity and PBFT /jsonrpc * gettransactionbyid / gettransactioninfobyid on solidity return standard {"Error":...} JSON instead of bare text * validateaddress, getBrokerage and getReward replace leaked library messages in their failure branches with existing fixed texts; the "INVALID address" body is now written via writeAuditedError and loses the space after the colon * getblock keeps its exact error bodies (refactor only) Cover Solidity transaction and transaction-info GET/POST input errors, backend failures, successful lookups and missing records directly with mocked Wallet calls and in-memory requests and responses. Replace the transaction servlet tests that accidentally exercised POST in both cases, changed global stdout and used a shared temporary response file. Verify both endpoint and global rate-limit rejections across the three JSON-RPC servlet variants, including status, response body and the absence of business dispatch on rejection. HTTP status codes, success responses, request validation rules and gRPC behavior are unchanged. JSON-RPC behavior is unchanged except for the shared HTTP rate-limit response described above. Closes #6936 * fix(api): keep server-side failure logging at error level The previous commit routed four catch-all blocks through the shared processError entry point, which logs at debug. Those four catches cover server-side work only: getburntrx, getnodeinfo and getpendingsize read no request parameters, and in getreward malformed addresses are already handled by the preceding DecoderException | IllegalArgumentException catch. Their failures therefore left no trace under the default log configuration, where the API topic is INFO. Add a dedicated processServerError entry point that logs at error and then applies the same sanitization, and use it at those four call sites. Logging the exception once inside the helper keeps a single record at any log level, instead of pairing an error log in the servlet with the debug log in the shared path. The shared Exception entry point keeps debug on purpose: its callers also cover request parsing, so an unauthenticated client can fail it cheaply and repeatedly, and an unconditional stack trace per request would amplify that into log pressure. Distinguishing client from server faults on that path is the parameter/internal split tracked as follow-up in #6936. Client-facing responses are unchanged. --- .../core/services/http/GetBlockServlet.java | 4 +- .../services/http/GetBrokerageServlet.java | 8 +- .../core/services/http/GetBurnTrxServlet.java | 8 +- .../services/http/GetNodeInfoServlet.java | 8 +- .../services/http/GetPendingSizeServlet.java | 8 +- .../core/services/http/GetRewardServlet.java | 15 +- .../GetTransactionInfoByBlockNumServlet.java | 15 +- .../services/http/RateLimiterServlet.java | 3 +- .../org/tron/core/services/http/Util.java | 48 ++- .../services/http/ValidateAddressServlet.java | 2 +- .../GetTransactionByIdSolidityServlet.java | 14 +- ...GetTransactionInfoByIdSolidityServlet.java | 15 +- .../services/http/BroadcastServletTest.java | 2 +- .../http/JsonRpcRateLimiterServletTest.java | 129 ++++++++ .../services/http/UtilProcessErrorTest.java | 107 +++++++ ...GetTransactionByIdSolidityServletTest.java | 286 +++++++----------- ...ransactionInfoByIdSolidityServletTest.java | 135 +++++++++ 17 files changed, 545 insertions(+), 262 deletions(-) create mode 100644 framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java diff --git a/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java index 2320fc87c7d..a953ae11802 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java @@ -77,9 +77,7 @@ private void fillResponse(boolean visible, BlockReq request, HttpServletResponse response.getWriter().println("{}"); } } catch (IllegalArgumentException e) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Error", e.getMessage()); - response.getWriter().println(jsonObject.toJSONString()); + Util.writeAuditedError(e.getMessage(), response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java index 1fbd94fe690..b735878d1e1 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -27,12 +26,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { } response.getWriter().println("{\"brokerage\": " + value + "}"); } catch (DecoderException | IllegalArgumentException e) { - try { - response.getWriter() - .println("{\"Error\": " + "\"INVALID address, " + e.getMessage() + "\"}"); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java index ea066a6e98c..3a19825ba75 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"burnTrxAmount\": " + value + "}"; response.getWriter().println(out); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java b/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java index 0b8f7b9ce2b..c8b4aa39785 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println(JSON.toJSONString(nodeInfo)); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java b/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java index 9788c926586..41a47c49001 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"pendingSize\": " + value + "}"; response.getWriter().println(out); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java index 61b88d1160f..780bab6ac94 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -29,19 +28,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"reward\": " + value + "}"; response.getWriter().println(out); } catch (DecoderException | IllegalArgumentException e) { - try { - response.getWriter() - .println("{\"Error\": " + "\"INVALID address, " + e.getMessage() + "\"}"); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java index 5d0a09b1a68..25998c909b6 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -52,12 +51,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println("{}"); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -75,12 +69,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println("{}"); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } } diff --git a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java index b5ae7d58623..6f67aba3020 100644 --- a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java @@ -131,8 +131,7 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) super.service(req, resp); Metrics.histogramObserve(requestTimer); } else { - resp.getWriter() - .println(Util.printErrorMsg(new IllegalAccessException("lack of computing resources"))); + Util.writeAuditedError(Util.RATE_LIMITER_ERROR_MSG, resp); } } catch (ServletException | IOException | BadMessageException e) { throw e; diff --git a/framework/src/main/java/org/tron/core/services/http/Util.java b/framework/src/main/java/org/tron/core/services/http/Util.java index 5be2495e1f7..ca20902c4d8 100644 --- a/framework/src/main/java/org/tron/core/services/http/Util.java +++ b/framework/src/main/java/org/tron/core/services/http/Util.java @@ -48,6 +48,8 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.config.args.Args; import org.tron.core.db.TransactionTrace; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.MaintenanceUnavailableException; import org.tron.core.services.http.JsonFormat.ParseException; import org.tron.json.JSON; import org.tron.json.JSONArray; @@ -65,6 +67,10 @@ @Slf4j(topic = "API") public class Util { + private static final String INTERNAL_SERVER_ERROR = "internal server error"; + public static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources"; + static final String INVALID_ADDRESS_MSG = "INVALID address"; + public static final String EVENTS_DEPRECATED_MSG = "'events' field is deprecated and no longer supported"; @@ -114,12 +120,31 @@ public static String printTransactionFee(String transactionFee) { return jsonObject.toJSONString(); } - public static String printErrorMsg(Exception e) { + private static String printErrorMsg(String msg) { JSONObject jsonObject = new JSONObject(); - jsonObject.put("Error", e.getClass() + " : " + e.getMessage()); + jsonObject.put("Error", msg); return jsonObject.toJSONString(); } + private static String clientMessage(Exception e) { + if (e == null) { + return INTERNAL_SERVER_ERROR; + } + + Class type = e.getClass(); + if (type == IllegalArgumentException.class) { + return EVENTS_DEPRECATED_MSG.equals(e.getMessage()) + ? EVENTS_DEPRECATED_MSG : INTERNAL_SERVER_ERROR; + } + if (type == ParseException.class + || type == ContractValidateException.class + || type == MaintenanceUnavailableException.class) { + String message = e.getMessage(); + return StringUtils.isBlank(message) ? INTERNAL_SERVER_ERROR : message; + } + return INTERNAL_SERVER_ERROR; + } + public static String printBlockList(BlockList list, boolean selfType) { List blocks = list.getBlockList(); JSONObject jsonObject = new JSONObject(); @@ -526,11 +551,24 @@ public static String getMemo(byte[] memo) { } public static void processError(Exception e, HttpServletResponse response) { - logger.debug(e.getMessage(), e); + logger.debug("HTTP request failed", e); + writeAuditedError(clientMessage(e), response); + } + + // For catch blocks that cover server-side work only, so the failure stays visible at the + // default log level. The Exception entry point above keeps debug because its callers also + // cover request parsing, which an unauthenticated client can fail cheaply and repeatedly. + static void processServerError(Exception e, HttpServletResponse response) { + logger.error("HTTP request failed", e); + writeAuditedError(clientMessage(e), response); + } + + // Bypasses clientMessage: callers must pass audited fixed or pre-existing client texts only. + static void writeAuditedError(String msg, HttpServletResponse response) { try { - response.getWriter().println(Util.printErrorMsg(e)); + response.getWriter().println(Util.printErrorMsg(msg)); } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); + logger.debug("Failed to write HTTP error response", ioe); } } diff --git a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java index 07eecfc5466..3ef45b42a7e 100644 --- a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java @@ -47,7 +47,7 @@ private String validAddress(String input) { } } catch (Exception e) { result = false; - msg = e.getMessage(); + msg = "Invalid address"; } JSONObject jsonAddress = new JSONObject(); diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java index f98c7450afc..5998bc0850f 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java @@ -30,12 +30,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { String input = request.getParameter("value"); fillResponse(ByteString.copyFrom(ByteArray.fromHexString(input)), visible, response); } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -46,12 +41,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) JsonFormat.merge(params.getParams(), build, params.isVisible()); fillResponse(build.build().getValue(), params.isVisible(), response); } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java index 0408215f09d..197f5aaec0d 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java @@ -1,7 +1,6 @@ package org.tron.core.services.http.solidity; import com.google.protobuf.ByteString; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -37,12 +36,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println(JsonFormat.printToString(transInfo, visible)); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -60,12 +54,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println(JsonFormat.printToString(transInfo, params.isVisible())); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } diff --git a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java index d6bf3850f30..532ddcd5521 100644 --- a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java @@ -156,7 +156,7 @@ public void doPostTest() throws IOException { while ((text = bufferedReader.readLine()) != null) { sb.append(text); } - Assert.assertTrue(sb.toString().contains("null")); + Assert.assertTrue(sb.toString().contains("{\"Error\":\"internal server error\"}")); httpUrlConnection.disconnect(); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java b/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java new file mode 100644 index 00000000000..52ff23a7d2d --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java @@ -0,0 +1,129 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.googlecode.jsonrpc4j.JsonRpcServer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.MockedStatic; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.TestConstants; +import org.tron.core.config.args.Args; +import org.tron.core.services.interfaceJsonRpcOnPBFT.JsonRpcOnPBFTServlet; +import org.tron.core.services.interfaceJsonRpcOnSolidity.JsonRpcOnSolidityServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; +import org.tron.core.services.interfaceOnSolidity.WalletOnSolidity; +import org.tron.core.services.jsonrpc.JsonRpcServlet; +import org.tron.core.services.ratelimiter.GlobalRateLimiter; +import org.tron.core.services.ratelimiter.RateLimiterContainer; +import org.tron.core.services.ratelimiter.RuntimeData; +import org.tron.core.services.ratelimiter.adapter.IRateLimiter; + +@RunWith(Parameterized.class) +public class JsonRpcRateLimiterServletTest { + + private final Class servletClass; + private RateLimiterServlet servlet; + private IRateLimiter perEndpoint; + private Object dispatcher; + private MockHttpServletRequest request; + private MockHttpServletResponse response; + + public JsonRpcRateLimiterServletTest(Class servletClass) { + this.servletClass = servletClass; + } + + @Parameterized.Parameters(name = "{0}") + public static Collection servlets() { + return Arrays.asList(new Object[][] { + {JsonRpcServlet.class}, + {JsonRpcOnSolidityServlet.class}, + {JsonRpcOnPBFTServlet.class} + }); + } + + @Before + public void setUp() throws Exception { + // Initialize Args before GlobalRateLimiter's static QPS limiters are loaded. + Args.setParam(new String[0], TestConstants.TEST_CONF); + servlet = servletClass.getDeclaredConstructor().newInstance(); + RateLimiterContainer container = new RateLimiterContainer(); + perEndpoint = mock(IRateLimiter.class); + container.add("http_", servletClass.getSimpleName(), perEndpoint); + ReflectionTestUtils.setField(servlet, "container", container); + + if (servlet instanceof JsonRpcOnSolidityServlet) { + dispatcher = mock(WalletOnSolidity.class); + ReflectionTestUtils.setField(servlet, "walletOnSolidity", dispatcher); + } else if (servlet instanceof JsonRpcOnPBFTServlet) { + dispatcher = mock(WalletOnPBFT.class); + ReflectionTestUtils.setField(servlet, "walletOnPBFT", dispatcher); + } else { + dispatcher = mock(JsonRpcServer.class); + ReflectionTestUtils.setField(servlet, "rpcServer", dispatcher); + } + + request = new MockHttpServletRequest("POST", "/jsonrpc"); + request.setServletPath("/jsonrpc"); + request.setRemoteAddr("10.0.0.1"); + request.setContentType("application/json"); + request.setContent("{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"id\":1}" + .getBytes(StandardCharsets.UTF_8)); + response = new MockHttpServletResponse(); + } + + @After + public void tearDown() { + Args.clearParam(); + } + + @Test + public void testPerEndpointRejectionReturnsSanitizedHttpError() throws Exception { + when(perEndpoint.acquirePermit(any(RuntimeData.class))).thenReturn(false); + + try (MockedStatic global = mockStatic(GlobalRateLimiter.class)) { + servlet.service(request, response); + + global.verify(() -> GlobalRateLimiter.acquirePermit(any()), never()); + assertRateLimitResponse(); + } + } + + @Test + public void testGlobalRejectionReturnsSanitizedHttpError() throws Exception { + when(perEndpoint.acquirePermit(any(RuntimeData.class))).thenReturn(true); + + try (MockedStatic global = mockStatic(GlobalRateLimiter.class)) { + global.when(() -> GlobalRateLimiter.acquirePermit(any())).thenReturn(false); + + servlet.service(request, response); + + global.verify(() -> GlobalRateLimiter.acquirePermit(any())); + assertRateLimitResponse(); + } + } + + private void assertRateLimitResponse() throws Exception { + assertEquals(200, response.getStatus()); + assertEquals("application/json; charset=utf-8", response.getContentType()); + assertEquals("{\"Error\":\"lack of computing resources\"}", + response.getContentAsString().trim()); + verify(perEndpoint).acquirePermit(any(RuntimeData.class)); + verifyNoInteractions(dispatcher); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java b/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java new file mode 100644 index 00000000000..5d4baa34c6f --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java @@ -0,0 +1,107 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import com.google.protobuf.InvalidProtocolBufferException; +import org.bouncycastle.util.encoders.DecoderException; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.MaintenanceUnavailableException; +import org.tron.core.exception.ZkProofValidateException; +import org.tron.json.JSONException; +import org.tron.json.JSONObject; + +public class UtilProcessErrorTest { + + private static final String INTERNAL_SERVER_ERROR = "internal server error"; + private static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources"; + + @Test + public void exactCompatibilityTypesPreserveNonBlankMessage() throws Exception { + assertError(new JsonFormat.ParseException("1:2: invalid \"field\"\nvalue"), + "1:2: invalid \"field\"\nvalue"); + assertError(new ContractValidateException("balance is not sufficient"), + "balance is not sufficient"); + assertError(new MaintenanceUnavailableException("maintenance in progress"), + "maintenance in progress"); + } + + @Test + public void unclassifiedTypesFailClosed() throws Exception { + DecoderException decoder = assertThrows(DecoderException.class, () -> Hex.decode("zz")); + Exception[] errors = { + new NullPointerException("internal field name"), + new JSONException("server serialization detail"), + new InvalidProtocolBufferException("stored protobuf detail"), + decoder, + new HeaderNotFound("latest block not found"), + new IllegalArgumentException("No enum constant internal.Type.VALUE"), + new IllegalAccessException(RATE_LIMITER_ERROR_MSG), + new IllegalAccessException("other access failure"), + new ZkProofValidateException("wrapped validation detail", true) + }; + + for (Exception error : errors) { + assertError(error, INTERNAL_SERVER_ERROR); + } + } + + @Test + public void onlyExactFixedControlSignalsArePreserved() throws Exception { + assertError(new IllegalArgumentException(Util.EVENTS_DEPRECATED_MSG), + Util.EVENTS_DEPRECATED_MSG); + assertError(new IllegalArgumentException("other argument failure"), INTERNAL_SERVER_ERROR); + assertError(new NumberFormatException(Util.EVENTS_DEPRECATED_MSG), INTERNAL_SERVER_ERROR); + } + + @Test + public void nullBlankAndSubclassMessagesFailClosed() throws Exception { + assertError(null, INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(null), INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(""), INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(" "), INTERNAL_SERVER_ERROR); + assertError(new ContractValidateException("subclass message") { }, INTERNAL_SERVER_ERROR); + } + + @Test + public void auditedErrorWriterPreservesTextVerbatim() throws Exception { + for (String audited : new String[] {Util.INVALID_ADDRESS_MSG, Util.RATE_LIMITER_ERROR_MSG}) { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.writeAuditedError(audited, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(audited, body.getString("Error")); + } + } + + @Test + public void auditedErrorWriterWithNullMessageWritesEmptyObject() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.writeAuditedError(null, response); + assertEquals("{}", response.getContentAsString().trim()); + } + + @Test + public void serverErrorChannelSanitizesLikeTheSharedPath() throws Exception { + assertServerError(new NullPointerException("internal field name"), INTERNAL_SERVER_ERROR); + assertServerError(new ContractValidateException("balance is not sufficient"), + "balance is not sufficient"); + } + + private static void assertServerError(Exception error, String expected) throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.processServerError(error, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(expected, body.getString("Error")); + } + + private static void assertError(Exception error, String expected) throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.processError(error, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(expected, body.getString("Error")); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java index e1abb41d1e1..cacb904d9b9 100644 --- a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java @@ -1,202 +1,146 @@ package org.tron.core.services.http.solidity; -import static org.mockito.BDDMockito.given; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLStreamHandlerFactory; -import java.nio.charset.StandardCharsets; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Collection; import org.junit.After; -import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.PublicMethod; -import org.tron.core.services.http.solidity.mockito.HttpUrlStreamHandler; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.Transaction; + +@RunWith(Parameterized.class) +public class GetTransactionByIdSolidityServletTest { + private static final String TRANSACTION_ID = + "309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef213f2c55225a8bd2"; + private static final ByteString TRANSACTION_ID_BYTES = + ByteString.copyFrom(ByteArray.fromHexString(TRANSACTION_ID)); -@Slf4j -public class GetTransactionByIdSolidityServletTest { + @Parameter + public String method; - private static HttpUrlStreamHandler httpUrlStreamHandler; - private GetTransactionByIdSolidityServlet getTransactionByIdSolidityServlet; - private HttpServletRequest request; - private HttpServletResponse response; - private HttpURLConnection httpUrlConnection; - private OutputStreamWriter outputStreamWriter; - private URL url; - - /** - * . - */ - @BeforeClass - public static void init() { - // Allows for mocking URL connections - URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); - try { - URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); - } catch (Error e) { - logger.info("Ignore error: {}", e.getMessage()); - } + private GetTransactionByIdSolidityServlet servlet; + private Wallet wallet; + private long savedMaxMessageSize; - httpUrlStreamHandler = new HttpUrlStreamHandler(); - given(urlStreamHandlerFactory.createURLStreamHandler("http")).willReturn(httpUrlStreamHandler); + @Parameters(name = "{0}") + public static Collection methods() { + return Arrays.asList(new Object[][] {{"GET"}, {"POST"}}); } - /** - * Init. - */ - @Before public void setUp() { - getTransactionByIdSolidityServlet = new GetTransactionByIdSolidityServlet(); - this.request = mock(HttpServletRequest.class); - this.response = mock(HttpServletResponse.class); - this.httpUrlConnection = mock(HttpURLConnection.class); - this.outputStreamWriter = mock(OutputStreamWriter.class); - httpUrlStreamHandler.resetConnections(); + savedMaxMessageSize = Args.getInstance().getHttpMaxMessageSize(); + Args.getInstance().setHttpMaxMessageSize(1024); + servlet = new GetTransactionByIdSolidityServlet(); + wallet = mock(Wallet.class); + ReflectionTestUtils.setField(servlet, "wallet", wallet); } - /** - * Release Resource. - */ @After public void tearDown() { - if (FileUtil.deleteDir(new File("temp.txt"))) { - logger.info("Release resources successful."); + Args.getInstance().setHttpMaxMessageSize(savedMaxMessageSize); + } + + @Test + public void walletFailureReturnsSanitizedJson() throws Exception { + when(wallet.getTransactionById(TRANSACTION_ID_BYTES)) + .thenThrow(new NullPointerException("internal transaction store detail")); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals("internal server error", errorMessage(response)); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); + } + + @Test + public void invalidHexReturnsJsonWithoutCallingWallet() throws Exception { + MockHttpServletResponse response = request("zz"); + + String message = errorMessage(response); + if ("GET".equals(method)) { + assertEquals("internal server error", message); } else { - logger.info("Release resources failure."); + assertTrue(message.matches("\\d+:\\d+: INVALID hex String")); } + verifyNoInteractions(wallet); } @Test - public void doPostTest() throws IOException { - - //send Post request - - final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:" - + PublicMethod.chooseRandomPort() + "/walletsolidity/gettransactioninfobyid"; - httpUrlStreamHandler.addConnection(new URL(href), httpUrlConnection); - httpUrlConnection.setRequestMethod("POST"); - httpUrlConnection.setRequestProperty("Content-Type", "application/json"); - httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); - httpUrlConnection.setUseCaches(false); - httpUrlConnection.setDoOutput(true); - String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" - + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); - - when(httpUrlConnection.getOutputStream()).thenReturn(outContent); - OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), - StandardCharsets.UTF_8); - out.write(postData); - out.flush(); - out.close(); - PrintWriter writer = new PrintWriter("temp.txt"); - when(response.getWriter()).thenReturn(writer); - - getTransactionByIdSolidityServlet.doPost(request, response); - // Get Response Body - String line; - StringBuilder result = new StringBuilder(); - - byte[] buffer = new byte[1024]; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); - when(httpUrlConnection.getInputStream()).thenReturn(byteArrayInputStream); - BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), - StandardCharsets.UTF_8)); - - while ((line = in.readLine()) != null) { - result.append(line).append("\n"); - } - Assert.assertNotNull(result); - in.close(); - writer.flush(); - FileInputStream fileInputStream = new FileInputStream("temp.txt"); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - - StringBuilder sb = new StringBuilder(); - String text; - while ((text = bufferedReader.readLine()) != null) { - sb.append(text); - } - Assert.assertTrue(sb.toString().contains("null")); - httpUrlConnection.disconnect(); + public void missingTransactionKeepsEmptyObject() throws Exception { + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + assertEquals("{}", response.getContentAsString().trim()); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); } @Test - public void doGetTest() throws IOException { - - final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:" - + PublicMethod.chooseRandomPort() + "/walletsolidity/gettransactioninfobyid"; - httpUrlStreamHandler.addConnection(new URL(href), httpUrlConnection); - httpUrlConnection.setRequestMethod("GET"); - httpUrlConnection.setRequestProperty("Content-Type", "application/json"); - httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); - httpUrlConnection.setUseCaches(false); - httpUrlConnection.setDoOutput(true); - String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" - + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); - - when(httpUrlConnection.getOutputStream()).thenReturn(outContent); - OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), - StandardCharsets.UTF_8); - out.write(postData); - out.flush(); - out.close(); - PrintWriter writer = new PrintWriter("temp.txt"); - when(response.getWriter()).thenReturn(writer); - - getTransactionByIdSolidityServlet.doPost(request, response); - // Get Response Body - String line; - StringBuilder result = new StringBuilder(); - - byte[] buffer = new byte[1024]; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); - when(httpUrlConnection.getInputStream()).thenReturn(byteArrayInputStream); - BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), - StandardCharsets.UTF_8)); - - while ((line = in.readLine()) != null) { - result.append(line).append("\n"); - } - Assert.assertNotNull(result); - in.close(); - writer.flush(); - FileInputStream fileInputStream = new FileInputStream("temp.txt"); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - - StringBuilder sb = new StringBuilder(); - String text; - while ((text = bufferedReader.readLine()) != null) { - sb.append(text); + public void successfulLookupKeepsTransaction() throws Exception { + ByteString signature = ByteString.copyFromUtf8("transaction signature"); + Transaction transaction = Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder().setTimestamp(123).setExpiration(456)) + .addSignature(signature).build(); + when(wallet.getTransactionById(TRANSACTION_ID_BYTES)).thenReturn(transaction); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(4, body.size()); + JSONObject rawData = body.getJSONObject("raw_data"); + assertEquals(123L, rawData.getLongValue("timestamp")); + assertEquals(456L, rawData.getLongValue("expiration")); + assertEquals(0, rawData.getJSONArray("contract").size()); + assertEquals(ByteArray.toHexString(transaction.getRawData().toByteArray()), + body.getString("raw_data_hex")); + assertEquals(Sha256Hash.of(Args.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()).toString(), body.getString("txID")); + assertEquals(1, body.getJSONArray("signature").size()); + assertEquals(ByteArray.toHexString(signature.toByteArray()), + body.getJSONArray("signature").getString(0)); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); + } + + private MockHttpServletResponse request(String value) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(method, + "/walletsolidity/gettransactionbyid"); + MockHttpServletResponse response = new MockHttpServletResponse(); + if ("GET".equals(method)) { + request.setParameter("value", value); + servlet.doGet(request, response); + } else { + request.setContentType("application/json"); + request.setContent(("{\"value\":\"" + value + "\"}").getBytes(UTF_8)); + servlet.doPost(request, response); } - Assert.assertTrue(sb.toString().contains("null")); - httpUrlConnection.disconnect(); + return response; } -} + private static String errorMessage(MockHttpServletResponse response) throws Exception { + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(1, body.size()); + return body.getString("Error"); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java new file mode 100644 index 00000000000..a8810114f82 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java @@ -0,0 +1,135 @@ +package org.tron.core.services.http.solidity; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Collection; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.TransactionInfo; + +@RunWith(Parameterized.class) +public class GetTransactionInfoByIdSolidityServletTest { + + private static final String TRANSACTION_ID = + "309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef213f2c55225a8bd2"; + private static final ByteString TRANSACTION_ID_BYTES = + ByteString.copyFrom(ByteArray.fromHexString(TRANSACTION_ID)); + + @Parameter + public String method; + + private GetTransactionInfoByIdSolidityServlet servlet; + private Wallet wallet; + private long savedMaxMessageSize; + + @Parameters(name = "{0}") + public static Collection methods() { + return Arrays.asList(new Object[][] {{"GET"}, {"POST"}}); + } + + @Before + public void setUp() { + savedMaxMessageSize = Args.getInstance().getHttpMaxMessageSize(); + Args.getInstance().setHttpMaxMessageSize(1024); + servlet = new GetTransactionInfoByIdSolidityServlet(); + wallet = mock(Wallet.class); + ReflectionTestUtils.setField(servlet, "wallet", wallet); + } + + @After + public void tearDown() { + Args.getInstance().setHttpMaxMessageSize(savedMaxMessageSize); + } + + @Test + public void walletFailureReturnsSanitizedJson() throws Exception { + when(wallet.getTransactionInfoById(TRANSACTION_ID_BYTES)) + .thenThrow(new NullPointerException("internal transaction store detail")); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals("internal server error", errorMessage(response)); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + @Test + public void invalidHexReturnsJsonWithoutCallingWallet() throws Exception { + MockHttpServletResponse response = request("zz"); + + String message = errorMessage(response); + if ("GET".equals(method)) { + assertEquals("internal server error", message); + } else { + assertTrue(message.matches("\\d+:\\d+: INVALID hex String")); + } + verifyNoInteractions(wallet); + } + + @Test + public void missingTransactionKeepsEmptyObject() throws Exception { + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + assertEquals("{}", response.getContentAsString().trim()); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + @Test + public void successfulLookupKeepsTransactionInfo() throws Exception { + TransactionInfo info = TransactionInfo.newBuilder() + .setId(TRANSACTION_ID_BYTES).setFee(7).setBlockNumber(123).build(); + when(wallet.getTransactionInfoById(TRANSACTION_ID_BYTES)).thenReturn(info); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(3, body.size()); + assertEquals(TRANSACTION_ID, body.getString("id")); + assertEquals(7L, body.getLongValue("fee")); + assertEquals(123L, body.getLongValue("blockNumber")); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + private MockHttpServletResponse request(String value) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(method, + "/walletsolidity/gettransactioninfobyid"); + MockHttpServletResponse response = new MockHttpServletResponse(); + if ("GET".equals(method)) { + request.setParameter("value", value); + servlet.doGet(request, response); + } else { + request.setContentType("application/json"); + request.setContent(("{\"value\":\"" + value + "\"}").getBytes(UTF_8)); + servlet.doPost(request, response); + } + return response; + } + + private static String errorMessage(MockHttpServletResponse response) throws Exception { + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(1, body.size()); + return body.getString("Error"); + } +} From bc7b5f758098b3fc010dea21031a80005ea37347 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 17 Sep 2026 15:05:15 +0800 Subject: [PATCH 8/8] refactor(rpc): serve solidity and pbft grpc via shared service instances Remove the duplicated wallet-solidity gRPC stack by serving the solidity and PBFT surfaces from the shared service instances, with a cursor interceptor selecting the store each call reads from. - Add cursor server interceptors for the solidity and PBFT ports and bind them to the shared services. - Serve solidity and PBFT gRPC through the shared service instances instead of separate handler implementations. - Deduplicate the remaining wallet-solidity read handlers. - Return after onError so a failed call is closed exactly once. - Document that the wallet-solidity API is the read-only subset of wallet, and assert that subset relationship in tests. - Cover the error path, cursor wiring and PBFT reads; drop probe tests that guarded nothing. --- .../org/tron/core/services/RpcApiService.java | 426 ++++------------ .../filter/CursorServerInterceptor.java | 52 ++ .../filter/PbftCursorInterceptor.java | 15 + .../filter/SolidityCursorInterceptor.java | 15 + .../interfaceOnPBFT/RpcApiServiceOnPBFT.java | 477 +----------------- .../RpcApiServiceOnSolidity.java | 470 +---------------- .../services/RpcApiServiceErrorPathTest.java | 140 +++++ .../core/services/RpcApiServicesTest.java | 2 + .../filter/CursorInterceptorScopeTest.java | 136 +++++ .../filter/CursorInterceptorServerTest.java | 123 +++++ .../filter/CursorInterceptorWiringTest.java | 101 ++++ 11 files changed, 690 insertions(+), 1267 deletions(-) create mode 100644 framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java create mode 100644 framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java create mode 100644 framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java create mode 100644 framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java create mode 100644 framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java create mode 100644 framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java create mode 100644 framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index b9cb05a3b14..5bea36bf632 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -181,6 +181,8 @@ public class RpcApiService extends RpcService { private MetricsApiService metricsApiService; @Getter private DatabaseApi databaseApi = new DatabaseApi(); + // WalletApi is the full protocol.Wallet impl (HEAD); WalletSolidityApi is its read-only subset, + // reused by the Solidity/PBFT cursor ports. private WalletApi walletApi = new WalletApi(); @Getter private WalletSolidityApi walletSolidityApi = new WalletSolidityApi(); @@ -362,249 +364,138 @@ public void getDynamicProperties(EmptyMessage request, } /** - * WalletSolidityApi. + * WalletSolidityApi is the full implementation of the {@code protocol.WalletSolidity} gRPC + * service. Every method here is read-only and also present on {@link WalletApi}, so each one + * delegates to the shared {@code WalletApi} singleton instead of repeating its body. */ public class WalletSolidityApi extends WalletSolidityImplBase { @Override public void getAccount(Account request, StreamObserver responseObserver) { - ByteString addressBs = request.getAddress(); - if (addressBs != null) { - Account reply = wallet.getAccount(request); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAccount(request, responseObserver); } @Override public void getAccountById(Account request, StreamObserver responseObserver) { - ByteString id = request.getAccountId(); - if (id != null) { - Account reply = wallet.getAccountById(request); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAccountById(request, responseObserver); } @Override public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getWitnessList()); - responseObserver.onCompleted(); + walletApi.listWitnesses(request, responseObserver); } @Override public void getPaginatedNowWitnessList(PaginatedMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext( - wallet.getPaginatedNowWitnessList(request.getOffset(), request.getLimit())); - } catch (MaintenanceUnavailableException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getPaginatedNowWitnessList(request, responseObserver); } @Override public void getAssetIssueList(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getAssetIssueList()); - responseObserver.onCompleted(); + walletApi.getAssetIssueList(request, responseObserver); } @Override public void getPaginatedAssetIssueList(PaginatedMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getAssetIssueList(request.getOffset(), request.getLimit())); - responseObserver.onCompleted(); + walletApi.getPaginatedAssetIssueList(request, responseObserver); } @Override public void getAssetIssueByName(BytesMessage request, StreamObserver responseObserver) { - ByteString assetName = request.getValue(); - if (assetName != null) { - try { - responseObserver.onNext(wallet.getAssetIssueByName(assetName)); - } catch (NonUniqueObjectException e) { - responseObserver.onNext(null); - logger.debug("Solidity NonUniqueObjectException: {}", e.getMessage()); - } - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueByName(request, responseObserver); } @Override public void getAssetIssueListByName(BytesMessage request, StreamObserver responseObserver) { - ByteString assetName = request.getValue(); - - if (assetName != null) { - responseObserver.onNext(wallet.getAssetIssueListByName(assetName)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueListByName(request, responseObserver); } @Override public void getAssetIssueById(BytesMessage request, StreamObserver responseObserver) { - ByteString assetId = request.getValue(); - - if (assetId != null) { - responseObserver.onNext(wallet.getAssetIssueById(assetId.toStringUtf8())); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueById(request, responseObserver); } @Override public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getNowBlock()); - responseObserver.onCompleted(); + walletApi.getNowBlock(request, responseObserver); } @Override public void getNowBlock2(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(block2Extention(wallet.getNowBlock())); - responseObserver.onCompleted(); + walletApi.getNowBlock2(request, responseObserver); } @Override public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - long num = request.getNum(); - if (num >= 0) { - Block reply = wallet.getBlockByNum(num); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getBlockByNum(request, responseObserver); } @Override public void getBlockByNum2(NumberMessage request, StreamObserver responseObserver) { - long num = request.getNum(); - if (num >= 0) { - Block reply = wallet.getBlockByNum(num); - responseObserver.onNext(block2Extention(reply)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getBlockByNum2(request, responseObserver); } @Override public void getDelegatedResource(DelegatedResourceMessage request, StreamObserver responseObserver) { - responseObserver - .onNext(wallet.getDelegatedResource(request.getFromAddress(), request.getToAddress())); - responseObserver.onCompleted(); + walletApi.getDelegatedResource(request, responseObserver); } @Override public void getDelegatedResourceV2(DelegatedResourceMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getDelegatedResourceV2( - request.getFromAddress(), request.getToAddress()) - ); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceV2(request, responseObserver); } @Override public void getDelegatedResourceAccountIndex(BytesMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getDelegatedResourceAccountIndex(request.getValue())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceAccountIndex(request, responseObserver); } @Override public void getDelegatedResourceAccountIndexV2(BytesMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getDelegatedResourceAccountIndexV2(request.getValue())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceAccountIndexV2(request, responseObserver); } @Override public void getCanDelegatedMaxSize(GrpcAPI.CanDelegatedMaxSizeRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getCanDelegatedMaxSize( - request.getOwnerAddress(),request.getType())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getCanDelegatedMaxSize(request, responseObserver); } @Override public void getAvailableUnfreezeCount(GrpcAPI.GetAvailableUnfreezeCountRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getAvailableUnfreezeCount( - request.getOwnerAddress())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getAvailableUnfreezeCount(request, responseObserver); } @Override public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getCanWithdrawUnfreezeAmount( - request.getOwnerAddress(), request.getTimestamp()) - ); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getCanWithdrawUnfreezeAmount(request, responseObserver); } @Override public void getExchangeById(BytesMessage request, StreamObserver responseObserver) { - ByteString exchangeId = request.getValue(); - - if (Objects.nonNull(exchangeId)) { - responseObserver.onNext(wallet.getExchangeById(exchangeId)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getExchangeById(request, responseObserver); } @Override public void listExchanges(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getExchangeList()); - responseObserver.onCompleted(); + walletApi.listExchanges(request, responseObserver); } @Override @@ -616,29 +507,13 @@ public void getTransactionCountByBlockNum(NumberMessage request, @Override public void getTransactionById(BytesMessage request, StreamObserver responseObserver) { - ByteString id = request.getValue(); - if (null != id) { - Transaction reply = wallet.getTransactionById(id); - - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getTransactionById(request, responseObserver); } @Override public void getTransactionInfoById(BytesMessage request, StreamObserver responseObserver) { - ByteString id = request.getValue(); - if (null != id) { - TransactionInfo reply = wallet.getTransactionInfoById(id); - - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getTransactionInfoById(request, responseObserver); } @Override @@ -661,198 +536,78 @@ public void getBurnTrx(EmptyMessage request, StreamObserver respo @Override public void getMerkleTreeVoucherInfo(OutputPointInfo request, StreamObserver responseObserver) { - - try { - IncrementalMerkleVoucherInfo witnessInfo = wallet - .getMerkleTreeVoucherInfo(request); - responseObserver.onNext(witnessInfo); - } catch (Exception ex) { - responseObserver.onError(getRunTimeException(ex)); - } - responseObserver.onCompleted(); + walletApi.getMerkleTreeVoucherInfo(request, responseObserver); } @Override public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - - try { - DecryptNotes decryptNotes = wallet - .scanNoteByIvk(startNum, endNum, request.getIvk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanNoteByIvk(request, responseObserver); } @Override public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - - try { - DecryptNotesMarked decryptNotes = wallet.scanAndMarkNoteByIvk(startNum, endNum, - request.getIvk().toByteArray(), - request.getAk().toByteArray(), - request.getNk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException | InvalidProtocolBufferException - | ItemNotFoundException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanAndMarkNoteByIvk(request, responseObserver); } @Override public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - try { - DecryptNotes decryptNotes = wallet - .scanNoteByOvk(startNum, endNum, request.getOvk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanNoteByOvk(request, responseObserver); } @Override public void isSpend(NoteParameters request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.isSpend(request)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.isSpend(request, responseObserver); } @Override public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, StreamObserver responseObserver) { - if (rejectIfEventsPresent(responseObserver, request.getEventsList())) { - return; - } - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - byte[] contractAddress = request.getShieldedTRC20ContractAddress().toByteArray(); - byte[] ivk = request.getIvk().toByteArray(); - byte[] ak = request.getAk().toByteArray(); - byte[] nk = request.getNk().toByteArray(); - - try { - responseObserver.onNext( - wallet.scanShieldedTRC20NotesByIvk(startNum, endNum, contractAddress, ivk, ak, nk)); - - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanShieldedTRC20NotesByIvk(request, responseObserver); } @Override public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, StreamObserver responseObserver) { - if (rejectIfEventsPresent(responseObserver, request.getEventsList())) { - return; - } - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - byte[] contractAddress = request.getShieldedTRC20ContractAddress().toByteArray(); - byte[] ovk = request.getOvk().toByteArray(); - try { - responseObserver - .onNext(wallet.scanShieldedTRC20NotesByOvk(startNum, endNum, ovk, contractAddress)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanShieldedTRC20NotesByOvk(request, responseObserver); } @Override public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.isShieldedTRC20ContractNoteSpent(request)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.isShieldedTRC20ContractNoteSpent(request, responseObserver); } @Override public void getMarketOrderByAccount(BytesMessage request, StreamObserver responseObserver) { - try { - ByteString address = request.getValue(); - - MarketOrderList marketOrderList = wallet - .getMarketOrderByAccount(address); - responseObserver.onNext(marketOrderList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderByAccount(request, responseObserver); } @Override public void getMarketOrderById(BytesMessage request, StreamObserver responseObserver) { - try { - ByteString address = request.getValue(); - - MarketOrder marketOrder = wallet - .getMarketOrderById(address); - responseObserver.onNext(marketOrder); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderById(request, responseObserver); } @Override public void getMarketPriceByPair(MarketOrderPair request, StreamObserver responseObserver) { - try { - MarketPriceList marketPriceList = wallet - .getMarketPriceByPair(request.getSellTokenId().toByteArray(), - request.getBuyTokenId().toByteArray()); - responseObserver.onNext(marketPriceList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketPriceByPair(request, responseObserver); } @Override public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, StreamObserver responseObserver) { - try { - MarketOrderList orderPairList = wallet - .getMarketOrderListByPair(request.getSellTokenId().toByteArray(), - request.getBuyTokenId().toByteArray()); - responseObserver.onNext(orderPairList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderListByPair(request, responseObserver); } @Override public void getMarketPairList(EmptyMessage request, StreamObserver responseObserver) { - try { - MarketOrderPairList pairList = wallet.getMarketPairList(); - responseObserver.onNext(pairList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketPairList(request, responseObserver); } @Override @@ -865,45 +620,13 @@ public void triggerConstantContract(TriggerSmartContract request, @Override public void estimateEnergy(TriggerSmartContract request, StreamObserver responseObserver) { - TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); - Return.Builder retBuilder = Return.newBuilder(); - EstimateEnergyMessage.Builder estimateBuilder - = EstimateEnergyMessage.newBuilder(); - - try { - TransactionCapsule trxCap = createTransactionCapsule(request, - ContractType.TriggerSmartContract); - wallet.estimateEnergy(request, trxCap, trxExtBuilder, retBuilder, estimateBuilder); - } catch (ContractValidateException | VMIllegalException e) { - retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(Wallet - .CONTRACT_VALIDATE_ERROR + e.getMessage())); - logger.warn(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); - } catch (RuntimeException e) { - retBuilder.setResult(false).setCode(response_code.CONTRACT_EXE_ERROR) - .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); - logger.warn("When run estimate energy in VM, have Runtime Exception: " + e.getMessage()); - } catch (Exception e) { - retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) - .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); - logger.warn(UNKNOWN_EXCEPTION_CAUGHT + e.getMessage(), e); - } finally { - estimateBuilder.setResult(retBuilder); - responseObserver.onNext(estimateBuilder.build()); - responseObserver.onCompleted(); - } + walletApi.estimateEnergy(request, responseObserver); } @Override public void getTransactionInfoByBlockNum(NumberMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getTransactionInfoByBlockNum(request.getNum())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - - responseObserver.onCompleted(); + walletApi.getTransactionInfoByBlockNum(request, responseObserver); } @Override @@ -915,23 +638,13 @@ public void getBlock(GrpcAPI.BlockReq request, @Override public void getBandwidthPrices(EmptyMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getBandwidthPrices()); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getBandwidthPrices(request, responseObserver); } @Override public void getEnergyPrices(EmptyMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getEnergyPrices()); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getEnergyPrices(request, responseObserver); } } @@ -953,7 +666,9 @@ private TransactionListExtention transactionList2Extention(TransactionList trans } /** - * WalletApi. + * WalletApi is the full implementation of the {@code protocol.Wallet} gRPC service, including + * write and build endpoints. {@link WalletSolidityApi} is the read-only subset of this surface + * and delegates its handlers here. */ public class WalletApi extends WalletImplBase { @@ -1479,15 +1194,26 @@ public void getNowBlock2(EmptyMessage request, @Override public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getBlockByNum(request.getNum())); + long num = request.getNum(); + if (num >= 0) { + Block reply = wallet.getBlockByNum(num); + responseObserver.onNext(reply); + } else { + responseObserver.onNext(null); + } responseObserver.onCompleted(); } @Override public void getBlockByNum2(NumberMessage request, StreamObserver responseObserver) { - Block block = wallet.getBlockByNum(request.getNum()); - responseObserver.onNext(block2Extention(block)); + long num = request.getNum(); + if (num >= 0) { + Block reply = wallet.getBlockByNum(num); + responseObserver.onNext(block2Extention(reply)); + } else { + responseObserver.onNext(null); + } responseObserver.onCompleted(); } @@ -1594,7 +1320,7 @@ public void getAssetIssueByName(BytesMessage request, responseObserver.onNext(wallet.getAssetIssueByName(assetName)); } catch (NonUniqueObjectException e) { responseObserver.onNext(null); - logger.debug("FullNode NonUniqueObjectException: {}", e.getMessage()); + logger.debug("NonUniqueObjectException: {}", e.getMessage()); } } else { responseObserver.onNext(null); @@ -1881,6 +1607,7 @@ public void getPaginatedNowWitnessList(PaginatedMessage request, wallet.getPaginatedNowWitnessList(request.getOffset(), request.getLimit())); } catch (MaintenanceUnavailableException e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1910,6 +1637,7 @@ public void getDelegatedResourceV2(DelegatedResourceMessage request, ); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1922,6 +1650,7 @@ public void getDelegatedResourceAccountIndex(BytesMessage request, .onNext(wallet.getDelegatedResourceAccountIndex(request.getValue())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1934,6 +1663,7 @@ public void getDelegatedResourceAccountIndexV2(BytesMessage request, .onNext(wallet.getDelegatedResourceAccountIndexV2(request.getValue())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1946,6 +1676,7 @@ public void getCanDelegatedMaxSize(GrpcAPI.CanDelegatedMaxSizeRequestMessage req request.getOwnerAddress(), request.getType())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -1959,6 +1690,7 @@ public void getAvailableUnfreezeCount(GrpcAPI.GetAvailableUnfreezeCountRequestMe request.getOwnerAddress())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -1974,6 +1706,7 @@ public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage )); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1985,6 +1718,7 @@ public void getBandwidthPrices(EmptyMessage request, responseObserver.onNext(wallet.getBandwidthPrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1996,6 +1730,7 @@ public void getEnergyPrices(EmptyMessage request, responseObserver.onNext(wallet.getEnergyPrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2007,6 +1742,7 @@ public void getMemoFee(EmptyMessage request, responseObserver.onNext(wallet.getMemoFeePrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2063,6 +1799,7 @@ public void getNodeInfo(EmptyMessage request, StreamObserver responseO responseObserver.onNext(nodeInfoService.getNodeInfo().transferToProtoEntity()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2539,6 +2276,7 @@ public void getTransactionInfoByBlockNum(NumberMessage request, responseObserver.onNext(wallet.getTransactionInfoByBlockNum(request.getNum())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -2568,6 +2306,7 @@ public void getMarketOrderByAccount(BytesMessage request, responseObserver.onNext(marketOrderList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2583,6 +2322,7 @@ public void getMarketOrderById(BytesMessage request, responseObserver.onNext(marketOrder); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2597,6 +2337,7 @@ public void getMarketPriceByPair(MarketOrderPair request, responseObserver.onNext(marketPriceList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2611,6 +2352,7 @@ public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair re responseObserver.onNext(orderPairList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2623,6 +2365,7 @@ public void getMarketPairList(EmptyMessage request, responseObserver.onNext(pairList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2672,6 +2415,7 @@ public void getRewardInfoCommon(BytesMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2685,6 +2429,7 @@ public void getBurnTrxCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2700,6 +2445,7 @@ public void getBrokerageInfoCommon(BytesMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2726,6 +2472,7 @@ public void getTransactionFromPendingCommon(BytesMessage request, responseObserver.onNext(transactionCapsule == null ? null : transactionCapsule.getInstance()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2738,6 +2485,7 @@ public void getTransactionListFromPendingCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2750,6 +2498,7 @@ public void getPendingSizeCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2765,6 +2514,7 @@ public void getBlockCommon(GrpcAPI.BlockReq request, } else { responseObserver.onError(getRunTimeException(e)); } + return; } responseObserver.onCompleted(); } diff --git a/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java new file mode 100644 index 00000000000..74d14daede9 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java @@ -0,0 +1,52 @@ +package org.tron.core.services.filter; + +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; + +/** + * Switches the current thread's read cursor around the synchronous handler callback and restores it + * afterwards, so the handler reads from the snapshot its subclass selects (HEAD / SOLIDITY / PBFT); + * the services behind it never touch the cursor. + * + *

Two invariants it relies on: + *

    + *
  • The bracket wraps {@code onHalfClose()} — where gRPC runs the unary handler inline — not + * {@code interceptCall}, which may land on another pool thread; the cursor is a + * {@link ThreadLocal}, so setting it elsewhere fails silently and the port serves HEAD. + *
  • Handlers must be synchronous: the cursor is reset when {@code onHalfClose} returns, so a read + * deferred to another thread would read HEAD. + *
+ * + *

The {@code finally} reset is mandatory: the fixed thread pool is reused, so a leftover cursor + * leaks into the next call on that thread. + */ +public abstract class CursorServerInterceptor implements ServerInterceptor { + + @Autowired + protected Manager dbManager; + + /** Snapshot every call on this server reads from; set by the subclass. */ + protected Chainbase.Cursor cursor; + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return new SimpleForwardingServerCallListener(next.startCall(call, headers)) { + @Override + public void onHalfClose() { + try { + dbManager.setCursor(cursor); + super.onHalfClose(); + } finally { + dbManager.resetCursor(); + } + } + }; + } +} diff --git a/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java new file mode 100644 index 00000000000..3ea55501d35 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java @@ -0,0 +1,15 @@ +package org.tron.core.services.filter; + +import org.springframework.stereotype.Component; +import org.tron.core.db2.core.Chainbase; + +/** + * Makes every call on the PBFT gRPC server read the PBFT-confirmed state view. + */ +@Component +public class PbftCursorInterceptor extends CursorServerInterceptor { + + public PbftCursorInterceptor() { + this.cursor = Chainbase.Cursor.PBFT; + } +} diff --git a/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java new file mode 100644 index 00000000000..5cf95ca0db4 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java @@ -0,0 +1,15 @@ +package org.tron.core.services.filter; + +import org.springframework.stereotype.Component; +import org.tron.core.db2.core.Chainbase; + +/** + * Makes every call on the Solidity gRPC server read the solidified state view. + */ +@Component +public class SolidityCursorInterceptor extends CursorServerInterceptor { + + public SolidityCursorInterceptor() { + this.cursor = Chainbase.Cursor.SOLIDITY; + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java index 54e7b69f7fc..2e6d1bd59bd 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java @@ -1,67 +1,22 @@ package org.tron.core.services.interfaceOnPBFT; +import io.grpc.ServerInterceptors; import io.grpc.netty.NettyServerBuilder; -import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.tron.api.DatabaseGrpc.DatabaseImplBase; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BlockReference; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeRequestMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeResponseMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountRequestMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage; -import org.tron.api.GrpcAPI.DecryptNotesTRC20; -import org.tron.api.GrpcAPI.DelegatedResourceList; -import org.tron.api.GrpcAPI.DelegatedResourceMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountRequestMessage; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountResponseMessage; -import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters; -import org.tron.api.GrpcAPI.NfTRC20Parameters; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NullifierResult; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.OvkDecryptTRC20Parameters; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.PricesResponseMessage; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.DynamicProperties; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPair; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.MarketPriceList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; - +import org.tron.core.services.filter.PbftCursorInterceptor; @Slf4j(topic = "API") public class RpcApiServiceOnPBFT extends RpcService { @Autowired - private WalletOnPBFT walletOnPBFT; + private RpcApiService rpcApiService; @Autowired - private RpcApiService rpcApiService; + private PbftCursorInterceptor pbftCursorInterceptor; public RpcApiServiceOnPBFT() { port = Args.getInstance().getRpcOnPBFTPort(); @@ -69,427 +24,13 @@ public RpcApiServiceOnPBFT() { executorName = "rpc-pbft-executor"; } + /** PBFT cursor bound at the service level, so it brackets only these two read services. */ @Override protected void addService(NettyServerBuilder serverBuilder) { - serverBuilder.addService(new DatabaseApi()); - serverBuilder.addService(new WalletPBFTApi()); + serverBuilder.addService( + ServerInterceptors.intercept(rpcApiService.getDatabaseApi(), pbftCursorInterceptor)); + serverBuilder.addService(ServerInterceptors.intercept( + rpcApiService.getWalletSolidityApi(), pbftCursorInterceptor)); } - /** - * DatabaseApi. - */ - private class DatabaseApi extends DatabaseImplBase { - - @Override - public void getBlockReference(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockReference(request, responseObserver) - ); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockByNum(request, responseObserver) - ); - } - - @Override - public void getDynamicProperties(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getDynamicProperties(request, responseObserver) - ); - } - } - - /** - * WalletPBFTApi. - */ - private class WalletPBFTApi extends WalletSolidityImplBase { - - @Override - public void getAccount(Account request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccount(request, responseObserver) - ); - } - - @Override - public void getAccountById(Account request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccountById(request, responseObserver) - ); - } - - @Override - public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().listWitnesses(request, responseObserver) - ); - } - - @Override - public void getAssetIssueById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueById(request, responseObserver) - ); - } - - @Override - public void getAssetIssueByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueByName(request, responseObserver) - ); - } - - @Override - public void getAssetIssueList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueList(request, responseObserver) - ); - } - - @Override - public void getAssetIssueListByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getAssetIssueListByName(request, responseObserver) - ); - } - - @Override - public void getPaginatedAssetIssueList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getPaginatedAssetIssueList(request, responseObserver) - ); - } - - @Override - public void getExchangeById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getExchangeById( - request, responseObserver - ) - ); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock(request, responseObserver) - ); - } - - @Override - public void getNowBlock2(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock2(request, responseObserver) - ); - - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum(request, responseObserver) - ); - } - - @Override - public void getBlockByNum2(NumberMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum2(request, responseObserver) - ); - } - - @Override - public void getDelegatedResource(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getDelegatedResource(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceV2(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceV2(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceAccountIndex(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndex(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceAccountIndexV2(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndexV2(request, responseObserver) - ); - } - - @Override - public void getCanDelegatedMaxSize(CanDelegatedMaxSizeRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getCanDelegatedMaxSize(request, responseObserver) - ); - } - - @Override - public void getAvailableUnfreezeCount(GetAvailableUnfreezeCountRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getAvailableUnfreezeCount(request, responseObserver) - ); - } - - @Override - public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getCanWithdrawUnfreezeAmount(request, responseObserver) - ); - } - - @Override - public void getTransactionCountByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getTransactionCountByBlockNum(request, responseObserver) - ); - } - - @Override - public void getTransactionById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getTransactionById(request, responseObserver) - ); - - } - - @Override - public void getTransactionInfoById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoById(request, responseObserver) - ); - - } - - @Override - public void listExchanges(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().listExchanges(request, responseObserver) - ); - } - - @Override - public void triggerConstantContract(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .triggerConstantContract(request, responseObserver) - ); - } - - @Override - public void estimateEnergy(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .estimateEnergy(request, responseObserver) - ); - } - - @Override - public void getRewardInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getRewardInfo(request, responseObserver) - ); - } - - @Override - public void getBrokerageInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBrokerageInfo(request, responseObserver) - ); - } - - @Override - public void getMerkleTreeVoucherInfo(OutputPointInfo request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMerkleTreeVoucherInfo(request, responseObserver) - ); - } - - @Override - public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByIvk(request, responseObserver) - ); - } - - @Override - public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanAndMarkNoteByIvk(request, responseObserver) - ); - } - - @Override - public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByOvk(request, responseObserver) - ); - } - - @Override - public void isSpend(NoteParameters request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().isSpend(request, responseObserver) - ); - } - - @Override - public void getMarketOrderByAccount(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderByAccount(request, responseObserver) - ); - } - - @Override - public void getMarketOrderById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderById(request, responseObserver) - ); - } - - @Override - public void getMarketPriceByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPriceByPair(request, responseObserver) - ); - } - - @Override - public void getMarketOrderListByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderListByPair(request, responseObserver) - ); - } - - @Override - public void getMarketPairList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPairList(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByIvk(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByOvk(request, responseObserver) - ); - } - - @Override - public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .isShieldedTRC20ContractNoteSpent(request, responseObserver) - ); - } - - @Override - public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) - ); - } - - @Override - public void getBlock(GrpcAPI.BlockReq request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlock(request, responseObserver)); - } - - @Override - public void getBandwidthPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); - } - - @Override - public void getEnergyPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); - } - - } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java index 315d70df8d6..f0c7b1468d2 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java @@ -1,70 +1,22 @@ package org.tron.core.services.interfaceOnSolidity; -import com.google.protobuf.ByteString; +import io.grpc.ServerInterceptors; import io.grpc.netty.NettyServerBuilder; -import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.tron.api.DatabaseGrpc.DatabaseImplBase; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BlockReference; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeRequestMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeResponseMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountRequestMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage; -import org.tron.api.GrpcAPI.DelegatedResourceList; -import org.tron.api.GrpcAPI.DelegatedResourceMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountRequestMessage; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountResponseMessage; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.PricesResponseMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.Sha256Hash; -import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.DynamicProperties; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPair; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.MarketPriceList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; - +import org.tron.core.services.filter.SolidityCursorInterceptor; @Slf4j(topic = "API") public class RpcApiServiceOnSolidity extends RpcService { - @Autowired - private WalletOnSolidity walletOnSolidity; + private RpcApiService rpcApiService; @Autowired - private RpcApiService rpcApiService; + private SolidityCursorInterceptor solidityCursorInterceptor; public RpcApiServiceOnSolidity() { port = Args.getInstance().getRpcOnSolidityPort(); @@ -72,417 +24,13 @@ public RpcApiServiceOnSolidity() { executorName = "rpc-solidity-executor"; } + /** SOLIDITY cursor bound at the service level, so it brackets only these two read services. */ @Override protected void addService(NettyServerBuilder serverBuilder) { - serverBuilder.addService(new DatabaseApi()); - serverBuilder.addService(new WalletSolidityApi()); + serverBuilder.addService( + ServerInterceptors.intercept(rpcApiService.getDatabaseApi(), solidityCursorInterceptor)); + serverBuilder.addService(ServerInterceptors.intercept( + rpcApiService.getWalletSolidityApi(), solidityCursorInterceptor)); } - private TransactionExtention transaction2Extention(Transaction transaction) { - if (transaction == null) { - return null; - } - TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); - Return.Builder retBuilder = Return.newBuilder(); - trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getByteString()); - retBuilder.setResult(true).setCode(response_code.SUCCESS); - trxExtBuilder.setResult(retBuilder); - return trxExtBuilder.build(); - } - - private BlockExtention block2Extention(Block block) { - if (block == null) { - return null; - } - BlockExtention.Builder builder = BlockExtention.newBuilder(); - BlockCapsule blockCapsule = new BlockCapsule(block); - builder.setBlockHeader(block.getBlockHeader()); - builder.setBlockid(ByteString.copyFrom(blockCapsule.getBlockId().getBytes())); - for (int i = 0; i < block.getTransactionsCount(); i++) { - Transaction transaction = block.getTransactions(i); - builder.addTransactions(transaction2Extention(transaction)); - } - return builder.build(); - } - - /** - * DatabaseApi. - */ - private class DatabaseApi extends DatabaseImplBase { - - @Override - public void getBlockReference(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockReference(request, responseObserver)); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getDatabaseApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getDatabaseApi().getBlockByNum(request, responseObserver)); - } - - @Override - public void getDynamicProperties(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getDatabaseApi().getDynamicProperties(request, responseObserver)); - } - } - - /** - * WalletSolidityApi. - */ - private class WalletSolidityApi extends WalletSolidityImplBase { - - @Override - public void getAccount(Account request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccount(request, responseObserver)); - } - - @Override - public void getAccountById(Account request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccountById(request, responseObserver)); - } - - @Override - public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().listWitnesses(request, responseObserver)); - } - - public void getPaginatedNowWitnessList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getPaginatedNowWitnessList(request, responseObserver)); - } - - @Override - public void getAssetIssueById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueById(request, responseObserver)); - } - - @Override - public void getAssetIssueByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAssetIssueByName(request, responseObserver)); - } - - @Override - public void getAssetIssueList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueList(request, responseObserver)); - } - - @Override - public void getAssetIssueListByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAssetIssueListByName(request, responseObserver)); - } - - @Override - public void getPaginatedAssetIssueList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getPaginatedAssetIssueList(request, responseObserver)); - } - - @Override - public void getExchangeById(BytesMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getExchangeById(request, responseObserver)); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getNowBlock2(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock2(request, responseObserver)); - - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum(request, responseObserver)); - } - - @Override - public void getBlockByNum2(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum2(request, responseObserver)); - } - - @Override - public void getDelegatedResource(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResource(request, responseObserver)); - } - - @Override - public void getDelegatedResourceV2(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceV2(request, responseObserver)); - } - - @Override - public void getDelegatedResourceAccountIndex(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndex(request, responseObserver)); - } - - @Override - public void getDelegatedResourceAccountIndexV2(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndexV2(request, responseObserver)); - } - - @Override - public void getCanDelegatedMaxSize(CanDelegatedMaxSizeRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getCanDelegatedMaxSize(request, responseObserver)); - } - - @Override - public void getAvailableUnfreezeCount(GetAvailableUnfreezeCountRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAvailableUnfreezeCount(request, responseObserver)); - } - - @Override - public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getCanWithdrawUnfreezeAmount(request, responseObserver)); - } - - @Override - public void getTransactionCountByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionCountByBlockNum(request, responseObserver)); - } - - @Override - public void getTransactionById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getTransactionById(request, responseObserver)); - - } - - @Override - public void getTransactionInfoById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoById(request, responseObserver)); - - } - - @Override - public void listExchanges(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().listExchanges(request, responseObserver)); - } - - @Override - public void triggerConstantContract(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .triggerConstantContract(request, responseObserver)); - } - - @Override - public void estimateEnergy(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .estimateEnergy(request, responseObserver)); - } - - @Override - public void getRewardInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getRewardInfo(request, responseObserver)); - } - - @Override - public void getBrokerageInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBrokerageInfo(request, responseObserver)); - } - - @Override - public void getMerkleTreeVoucherInfo(OutputPointInfo request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getMerkleTreeVoucherInfo(request, responseObserver)); - } - - @Override - public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByIvk(request, responseObserver)); - } - - @Override - public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .scanAndMarkNoteByIvk(request, responseObserver)); - } - - @Override - public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByOvk(request, responseObserver)); - } - - @Override - public void isSpend(NoteParameters request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getWalletSolidityApi().isSpend(request, responseObserver)); - } - - @Override - public void getTransactionInfoByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoByBlockNum(request, responseObserver)); - } - - @Override - public void scanShieldedTRC20NotesByIvk(GrpcAPI.IvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByIvk(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByOvk(GrpcAPI.OvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByOvk(request, responseObserver) - ); - } - - @Override - public void isShieldedTRC20ContractNoteSpent(GrpcAPI.NfTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .isShieldedTRC20ContractNoteSpent(request, responseObserver) - ); - } - - @Override - public void getMarketOrderByAccount(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderByAccount(request, responseObserver) - ); - } - - @Override - public void getMarketOrderById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderById(request, responseObserver) - ); - } - - @Override - public void getMarketPriceByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPriceByPair(request, responseObserver) - ); - } - - @Override - public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderListByPair(request, responseObserver) - ); - } - - @Override - public void getMarketPairList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPairList(request, responseObserver) - ); - } - - @Override - public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) - ); - } - - @Override - public void getBlock(GrpcAPI.BlockReq request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlock(request, responseObserver)); - } - - @Override - public void getBandwidthPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); - } - - @Override - public void getEnergyPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); - } - - } } diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java new file mode 100644 index 00000000000..16437f139e7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java @@ -0,0 +1,140 @@ +package org.tron.core.services; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + +import com.google.protobuf.Message; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.stubbing.Answer; +import org.tron.core.Wallet; +import org.tron.core.metrics.MetricsApiService; +import org.tron.core.services.RpcApiService.WalletApi; +import org.tron.core.services.RpcApiService.WalletSolidityApi; +import org.tron.core.utils.TransactionUtil; + +/** + * Pins the one-terminal-event rule on the gRPC error path: a handler that reports a failure through + * {@code onError} must not fall through to {@code onCompleted}. gRPC rejects the second close with + * {@code IllegalStateException("call already closed")}, so a handler doing both costs a server-side + * exception on every failed call while the client sees nothing extra. + * + *

The rule is checked for every handler rather than for the ones that were fixed, because the + * shape is trivially reintroduced by copying a neighbouring handler. + */ +public class RpcApiServiceErrorPathTest { + + /** Minimum handlers that must actually fail, so the sweep cannot silently cover nothing. */ + private static final int MIN_EXERCISED = 20; + + @Test + public void testWalletApiTerminatesTheCallOnce() throws Exception { + assertSingleTerminalEvent(WalletApi.class); + } + + @Test + public void testWalletSolidityApiTerminatesTheCallOnce() throws Exception { + assertSingleTerminalEvent(WalletSolidityApi.class); + } + + /** + * Drives every unary handler of the given service class with collaborators that throw, and + * asserts none of them terminates the call more than once. + */ + private static void assertSingleTerminalEvent(Class apiClass) throws Exception { + RpcApiService service = mock(RpcApiService.class, + withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + injectThrowingCollaborators(service); + Object api = apiClass.getDeclaredConstructor(RpcApiService.class).newInstance(service); + + int exercised = 0; + for (Method method : apiClass.getDeclaredMethods()) { + if (!isUnaryHandler(method)) { + continue; + } + Message request = (Message) method.getParameterTypes()[0] + .getMethod("getDefaultInstance").invoke(null); + TerminalRecorder recorder = new TerminalRecorder(); + try { + method.invoke(api, request, recorder); + } catch (InvocationTargetException e) { + // a handler that lets the failure escape cannot have closed the call twice + continue; + } + Assert.assertTrue( + method.getName() + " terminated the call " + recorder.events.size() + " times " + + recorder.events + "; onError must be followed by return", + recorder.events.size() <= 1); + if (!recorder.events.isEmpty()) { + exercised++; + } + } + Assert.assertTrue( + apiClass.getSimpleName() + " exercised only " + exercised + " handlers, expected at least " + + MIN_EXERCISED + " — the sweep is no longer reaching the handler bodies", + exercised >= MIN_EXERCISED); + } + + private static boolean isUnaryHandler(Method method) { + Class[] params = method.getParameterTypes(); + return Modifier.isPublic(method.getModifiers()) + && method.getReturnType() == void.class + && params.length == 2 + && Message.class.isAssignableFrom(params[0]) + && params[1] == StreamObserver.class; + } + + /** + * Replaces the service's collaborators with mocks that throw on every call, so each handler takes + * its own error path, and binds a real {@code WalletApi} for the solidity handlers to delegate + * to. + */ + private static void injectThrowingCollaborators(RpcApiService service) throws Exception { + Answer throwing = invocation -> { + throw new RuntimeException("collaborator unavailable"); + }; + set(service, "wallet", mock(Wallet.class, withSettings().defaultAnswer(throwing))); + set(service, "transactionUtil", + mock(TransactionUtil.class, withSettings().defaultAnswer(throwing))); + set(service, "nodeInfoService", + mock(NodeInfoService.class, withSettings().defaultAnswer(throwing))); + set(service, "metricsApiService", + mock(MetricsApiService.class, withSettings().defaultAnswer(throwing))); + set(service, "walletApi", + WalletApi.class.getDeclaredConstructor(RpcApiService.class).newInstance(service)); + } + + private static void set(RpcApiService service, String name, Object value) throws Exception { + Field field = RpcApiService.class.getDeclaredField(name); + field.setAccessible(true); + field.set(service, value); + } + + /** Counts terminal events instead of closing a real call. */ + private static final class TerminalRecorder implements StreamObserver { + + private final List events = new ArrayList<>(); + + @Override + public void onNext(Object value) { + } + + @Override + public void onError(Throwable t) { + events.add("onError"); + } + + @Override + public void onCompleted() { + events.add("onCompleted"); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index c3ac5800971..3df54b9c0f9 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -277,6 +277,7 @@ public void testGetPaginatedNowWitnessList() { .setOffset(0).setLimit(5).build(); assertNotNull(blockingStubFull.getPaginatedNowWitnessList(paginatedMessage)); assertNotNull(blockingStubSolidity.getPaginatedNowWitnessList(paginatedMessage)); + assertNotNull(blockingStubPBFT.getPaginatedNowWitnessList(paginatedMessage)); } @Test @@ -673,6 +674,7 @@ public void testGetTransactionInfoByBlockNum() { NumberMessage message = NumberMessage.newBuilder().setNum(1).build(); assertNotNull(blockingStubFull.getTransactionInfoByBlockNum(message)); assertNotNull(blockingStubSolidity.getTransactionInfoByBlockNum(message)); + assertNotNull(blockingStubPBFT.getTransactionInfoByBlockNum(message)); } @Test diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java new file mode 100644 index 00000000000..54e82426c0c --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java @@ -0,0 +1,136 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; + +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import java.lang.reflect.Field; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; + +/** + * Pins the cursor's scope without depending on thread-pool scheduling. + * + *

{@code interceptCall()} is driven on thread A and the returned listener's + * {@code onHalfClose()} on a different thread B, which is what gRPC's {@code SerializingExecutor} + * is free to do. An implementation that scoped the cursor around {@code interceptCall} instead of + * {@code onHalfClose} then fails here by construction rather than by luck. + */ +public class CursorInterceptorScopeTest { + + private ExecutorService threadA; + private ExecutorService threadB; + + private Manager manager; + private Chainbase.Cursor cursorDuringHandler; + private Chainbase.Cursor cursorAfterCall; + private Chainbase.Cursor current; + + @Before + public void setUp() { + threadA = Executors.newSingleThreadExecutor(r -> new Thread(r, "cursor-thread-A")); + threadB = Executors.newSingleThreadExecutor(r -> new Thread(r, "cursor-thread-B")); + + // a Manager whose cursor state is observable, standing in for the ThreadLocal in Chainbase + current = Chainbase.Cursor.HEAD; + manager = mock(Manager.class); + doAnswer(inv -> current = inv.getArgument(0)) + .when(manager).setCursor(any(Chainbase.Cursor.class)); + doAnswer(inv -> current = Chainbase.Cursor.HEAD).when(manager).resetCursor(); + } + + @After + public void tearDown() throws Exception { + threadA.shutdownNow(); + threadB.shutdownNow(); + threadA.awaitTermination(5, TimeUnit.SECONDS); + threadB.awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + public void testHandlerSeesTheCursorWhenInterceptCallRanOnAnotherThread() throws Exception { + ServerCall.Listener listener = startCallOnThreadA(false); + + // the handler runs from onHalfClose, on a different thread than interceptCall + runOn(threadB, () -> { + listener.onHalfClose(); + return null; + }); + + Assert.assertEquals("handler must observe the SOLIDITY cursor", + Chainbase.Cursor.SOLIDITY, cursorDuringHandler); + Assert.assertEquals("cursor must be back at HEAD once the handler returns", + Chainbase.Cursor.HEAD, cursorAfterCall); + } + + @Test + public void testCursorIsRestoredOnThreadBWhenTheHandlerThrows() throws Exception { + ServerCall.Listener listener = startCallOnThreadA(true); + + try { + runOn(threadB, () -> { + listener.onHalfClose(); + return null; + }); + Assert.fail("expected the handler failure to propagate"); + } catch (Exception expected) { + // what matters is the cursor state below + } + + Assert.assertEquals("a throwing handler must still leave the cursor at HEAD", + Chainbase.Cursor.HEAD, current); + } + + /** Runs interceptCall on thread A and returns the listener, with a handler that records state. */ + private ServerCall.Listener startCallOnThreadA(boolean handlerThrows) throws Exception { + SolidityCursorInterceptor interceptor = new SolidityCursorInterceptor(); + Field dbManager = CursorServerInterceptor.class.getDeclaredField("dbManager"); + dbManager.setAccessible(true); + dbManager.set(interceptor, manager); + + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + MethodDescriptor descriptor = mock(MethodDescriptor.class); + doAnswer(inv -> descriptor).when(call).getMethodDescriptor(); + + ServerCallHandler handler = (c, h) -> new ServerCall.Listener() { + @Override + public void onHalfClose() { + cursorDuringHandler = current; + if (handlerThrows) { + throw new IllegalStateException("boom"); + } + } + }; + + return runOn(threadA, () -> { + ServerCall.Listener l = interceptor.interceptCall(call, new Metadata(), handler); + cursorAfterCall = current; + return l; + }); + } + + private static T runOn(ExecutorService executor, Callable task) throws Exception { + try { + return executor.submit(task).get(5, TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException e) { + if (e.getCause() instanceof Exception) { + throw (Exception) e.getCause(); + } + throw e; + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java new file mode 100644 index 00000000000..57babc52051 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java @@ -0,0 +1,123 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Field; +import java.net.ServerSocket; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.DatabaseGrpc; +import org.tron.api.DatabaseGrpc.DatabaseImplBase; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; +import org.tron.protos.Protocol.Block; + +/** + * Drives the production interceptor through a real gRPC server, which is the only place the + * assumption it rests on can be checked: that gRPC runs the handler inline from + * {@code onHalfClose}, on the same thread. The cursor is a {@link ThreadLocal}, so if that stops + * holding the cursor never reaches the read path and the port serves HEAD data with no error — + * responses stay well-formed, so nothing else notices. + * + *

CursorInterceptorScopeTest covers the interceptor's own logic on a synthetic harness; this is + * the end-to-end half. + */ +public class CursorInterceptorServerTest { + + private ExecutorService executor; + + @Before + public void setUp() { + // a fixed thread pool mirrors the production server configuration + executor = Executors.newFixedThreadPool(2, r -> { + Thread thread = new Thread(r); + thread.setName("cursor-rpc-executor-" + thread.getId()); + return thread; + }); + } + + @After + public void tearDown() throws Exception { + if (executor != null) { + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + } + } + } + + @Test + public void testCursorIsSetAndRestoredOnTheHandlerThread() throws Exception { + final List setOn = new CopyOnWriteArrayList<>(); + final List resetOn = new CopyOnWriteArrayList<>(); + final String[] handlerOn = new String[1]; + + Manager manager = mock(Manager.class); + doAnswer(inv -> setOn.add(Thread.currentThread().getName())) + .when(manager).setCursor(any(Chainbase.Cursor.class)); + doAnswer(inv -> resetOn.add(Thread.currentThread().getName())) + .when(manager).resetCursor(); + + SolidityCursorInterceptor interceptor = new SolidityCursorInterceptor(); + Field dbManager = CursorServerInterceptor.class.getDeclaredField("dbManager"); + dbManager.setAccessible(true); + dbManager.set(interceptor, manager); + + int port = freePort(); + Server server = ServerBuilder.forPort(port) + .executor(executor) + .addService(new DatabaseImplBase() { + @Override + public void getNowBlock(EmptyMessage request, StreamObserver observer) { + handlerOn[0] = Thread.currentThread().getName(); + observer.onNext(Block.getDefaultInstance()); + observer.onCompleted(); + } + }) + .intercept(interceptor) + .build() + .start(); + + ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port) + .usePlaintext().directExecutor().build(); + try { + DatabaseGrpc.newBlockingStub(channel).getNowBlock(EmptyMessage.getDefaultInstance()); + + Assert.assertEquals("cursor must be set exactly once per call", 1, setOn.size()); + Assert.assertEquals("cursor must be restored exactly once per call", 1, resetOn.size()); + Assert.assertNotNull("handler did not run", handlerOn[0]); + // the ThreadLocal cursor only reaches the read path if it is set on the handler's thread + Assert.assertEquals("cursor was set on a thread other than the handler's", + handlerOn[0], setOn.get(0)); + Assert.assertEquals("cursor was restored on a thread other than the handler's", + handlerOn[0], resetOn.get(0)); + verify(manager).setCursor(Chainbase.Cursor.SOLIDITY); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + server.awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static int freePort() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java new file mode 100644 index 00000000000..5f403b9d742 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java @@ -0,0 +1,101 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.withSettings; + +import io.grpc.BindableService; +import io.grpc.ServerServiceDefinition; +import io.grpc.netty.NettyServerBuilder; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.ArgumentCaptor; +import org.tron.api.DatabaseGrpc; +import org.tron.api.WalletSolidityGrpc; +import org.tron.core.services.RpcApiService; +import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; +import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; + +/** + * Guards that each cursor gRPC service registers the shared read services through its + * cursor interceptor. Nothing else catches a dropped interceptor: the services would still be + * served and every response would still look well-formed, only resolved against HEAD instead of the + * solidified or PBFT snapshot. This is the gRPC counterpart of CursorFilterInstallationTest. + * + *

Registering without the interceptor binds the {@code addService(BindableService)} overload + * rather than the {@code addService(ServerServiceDefinition)} one, so the two are distinguishable + * here. What the interceptor does once attached is pinned by CursorInterceptorScopeTest and + * CursorInterceptorServerTest. + */ +public class CursorInterceptorWiringTest { + + private static final Set SHARED_READ_SERVICES = new HashSet<>( + Arrays.asList(DatabaseGrpc.SERVICE_NAME, WalletSolidityGrpc.SERVICE_NAME)); + + @Test + public void testSolidityServiceRegistersBothReadServicesThroughTheCursor() throws Exception { + Assert.assertEquals(SHARED_READ_SERVICES, + interceptedServices(RpcApiServiceOnSolidity.class, new SolidityCursorInterceptor())); + } + + @Test + public void testPbftServiceRegistersBothReadServicesThroughTheCursor() throws Exception { + Assert.assertEquals(SHARED_READ_SERVICES, + interceptedServices(RpcApiServiceOnPBFT.class, new PbftCursorInterceptor())); + } + + /** + * Runs the service's real addService against a mock builder and returns the names of the services + * it registered as intercepted definitions, failing if any was registered unintercepted. + */ + private static Set interceptedServices(Class serviceClass, + CursorServerInterceptor interceptor) throws Exception { + RpcApiService rpcApiService = mock(RpcApiService.class); + given(rpcApiService.getDatabaseApi()).willReturn(RpcApiService.DatabaseApi.class + .getDeclaredConstructor(RpcApiService.class).newInstance(rpcApiService)); + given(rpcApiService.getWalletSolidityApi()).willReturn(RpcApiService.WalletSolidityApi.class + .getDeclaredConstructor(RpcApiService.class).newInstance(rpcApiService)); + + Object service = mock(serviceClass, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + inject(serviceClass, service, rpcApiService); + inject(serviceClass, service, interceptor); + + NettyServerBuilder builder = mock(NettyServerBuilder.class); + Method addService = serviceClass.getDeclaredMethod("addService", NettyServerBuilder.class); + addService.setAccessible(true); + addService.invoke(service, builder); + + verify(builder, never()).addService(any(BindableService.class)); + ArgumentCaptor registered = + ArgumentCaptor.forClass(ServerServiceDefinition.class); + verify(builder, times(2)).addService(registered.capture()); + + Set names = new HashSet<>(); + for (ServerServiceDefinition definition : registered.getAllValues()) { + names.add(definition.getServiceDescriptor().getName()); + } + return names; + } + + /** Sets the one declared field the value fits; the two injected types are unrelated. */ + private static void inject(Class serviceClass, Object service, Object value) throws Exception { + for (Field field : serviceClass.getDeclaredFields()) { + if (field.getType().isInstance(value)) { + field.setAccessible(true); + field.set(service, value); + return; + } + } + Assert.fail(serviceClass.getSimpleName() + " has no field for " + value.getClass().getName()); + } +}