From 4d6d5c63c95ed92102fbdb2b44eb13d312945205 Mon Sep 17 00:00:00 2001 From: halibobo1205 Date: Thu, 28 Nov 2024 11:39:12 +0800 Subject: [PATCH] feat(math): migrate all operations from java.lang.Math to java.lang.StrictMath --- .github/workflows/math-check.yml | 93 +++++++++++ .../AccountPermissionUpdateActuator.java | 3 +- .../core/actuator/ExchangeInjectActuator.java | 11 +- .../actuator/ExchangeWithdrawActuator.java | 8 - .../actuator/MarketSellAssetActuator.java | 15 +- .../ParticipateAssetIssueActuator.java | 21 ++- .../actuator/ShieldedTransferActuator.java | 16 +- .../tron/core/actuator/TransferActuator.java | 7 +- .../core/actuator/TransferAssetActuator.java | 4 +- .../actuator/UnDelegateResourceActuator.java | 5 +- .../org/tron/core/actuator/VMActuator.java | 28 ++-- .../org/tron/core/utils/TransactionUtil.java | 7 +- .../tron/core/vm/PrecompiledContracts.java | 9 +- .../main/java/org/tron/core/vm/VMUtils.java | 5 +- .../UnDelegateResourceProcessor.java | 5 +- .../java/org/tron/core/vm/program/Memory.java | 13 +- .../org/tron/core/vm/program/Program.java | 19 ++- .../core/vm/repository/RepositoryImpl.java | 8 +- .../org/tron/core/vm/utils/FreezeV2Util.java | 14 +- .../java/org/tron/common/utils/Commons.java | 9 +- .../org/tron/common/utils/ForkController.java | 4 +- .../org/tron/core/capsule/AccountCapsule.java | 53 +++---- .../tron/core/capsule/ContractCapsule.java | 5 +- .../core/capsule/ContractStateCapsule.java | 6 +- .../org/tron/core/capsule/ReceiptCapsule.java | 13 +- .../tron/core/capsule/utils/MarketUtils.java | 14 +- .../org/tron/core/db/EnergyProcessor.java | 6 +- .../org/tron/core/db/ResourceProcessor.java | 12 +- .../org/tron/core/db/TransactionTrace.java | 8 +- .../tron/core/service/MortgageService.java | 4 +- .../org/tron/core/store/AssetIssueStore.java | 7 - .../core/store/DynamicPropertiesStore.java | 7 +- .../tron/common/math/StrictMathWrapper.java | 147 ++++++++++++++++++ .../org/tron/common/runtime/vm/DataWord.java | 7 +- .../java/org/tron/common/utils/ByteUtil.java | 6 +- .../logsfilter/ContractEventParser.java | 4 +- .../src/main/java/org/tron/core/Wallet.java | 17 +- .../java/org/tron/core/capsule/utils/RLP.java | 3 +- .../java/org/tron/core/config/args/Args.java | 25 ++- .../main/java/org/tron/core/db/Manager.java | 15 +- .../SyncBlockChainMsgHandler.java | 4 +- .../service/effective/ResilienceService.java | 7 +- .../jsonrpc/filters/LogFilterWrapper.java | 4 +- .../main/java/org/tron/program/DBConvert.java | 3 +- .../runtime/vm/BandWidthRuntimeTest.java | 4 +- .../tron/common/runtime/vm/FreezeV2Test.java | 3 +- .../tron/common/runtime/vm/MemoryTest.java | 4 +- .../PrecompiledContractsVerifyProofTest.java | 4 +- .../org/tron/common/runtime/vm/VoteTest.java | 3 +- .../common/utils/client/utils/AbiUtil.java | 4 +- .../common/utils/client/utils/DataWord.java | 4 +- .../actuator/utils/TransactionUtilTest.java | 13 +- .../core/capsule/utils/MerkleTreeTest.java | 4 +- .../db/MarketPairPriceToOrderStoreTest.java | 5 +- .../core/jsonrpc/ConcurrentHashMapTest.java | 5 +- .../tron/core/zksnark/LibrustzcashTest.java | 4 +- .../tron/core/zksnark/SaplingNoteTest.java | 5 +- .../org/tron/plugins/utils/ByteArray.java | 2 +- .../java/org/tron/plugins/utils/DBUtils.java | 3 +- .../org/tron/plugins/utils/MarketUtils.java | 4 +- 60 files changed, 536 insertions(+), 216 deletions(-) create mode 100644 .github/workflows/math-check.yml diff --git a/.github/workflows/math-check.yml b/.github/workflows/math-check.yml new file mode 100644 index 00000000000..0f0255815d5 --- /dev/null +++ b/.github/workflows/math-check.yml @@ -0,0 +1,93 @@ +name: Check Math Usage + +on: + push: + branches: [ 'master', 'release_**' ] + pull_request: + branches: [ 'develop', 'release_**' ] + workflow_dispatch: + +jobs: + check-math: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check for java.lang.Math usage + id: check-math + shell: bash + run: | + echo "Checking for java.lang.Math usage..." + + touch math_usage.txt + + while IFS= read -r file; do + filename=$(basename "$file") + if [[ "$filename" == "StrictMathWrapper.java" || "$filename" == "MathWrapper.java" ]]; then + continue + fi + + perl -0777 -ne ' + s/"([^"\\]|\\.)*"//g; + s/'\''([^'\''\\]|\\.)*'\''//g; + s!/\*([^*]|\*[^/])*\*/!!g; + s!//[^\n]*!!g; + $hasMath = 0; + $hasMath = 1 if /^[\s]*import[\s]+java\.lang\.Math\b/m; + $hasMath = 1 if /\bjava\s*\.\s*lang\s*\.\s*Math\s*\./; + $hasMath = 1 if /(?> math_usage.txt + done < <(find . -type f -name "*.java") + + sort -u math_usage.txt -o math_usage.txt + + if [ -s math_usage.txt ]; then + echo "❌ Error: Forbidden Math usage found in the following files:" + cat math_usage.txt + echo "math_found=true" >> $GITHUB_OUTPUT + echo "Please use org.tron.common.math.StrictMathWrapper instead of direct Math usage." + else + echo "✅ No forbidden Math usage found" + echo "math_found=false" >> $GITHUB_OUTPUT + fi + + - name: Upload findings + if: steps.check-math.outputs.math_found == 'true' + uses: actions/upload-artifact@v4 + with: + name: math-usage-report + path: math_usage.txt + + - name: Create comment + if: github.event_name == 'pull_request' && steps.check-math.outputs.math_found == 'true' + uses: actions/github-script@v6 + with: + script: | + const fs = require('fs'); + const findings = fs.readFileSync('math_usage.txt', 'utf8'); + const body = `### ❌ Math Usage Detection Results + + Found forbidden usage of \`java.lang.Math\` in the following files: + + \`\`\` + ${findings} + \`\`\` + + **Please review if this usage is intended.** + > [!CAUTION] + > Note: You should use \`org.tron.common.math.StrictMathWrapper\`. + > If you need to use \`java.lang.Math\`, please provide a justification. + `; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: body + }); + + - name: Fail if Math usage found + if: steps.check-math.outputs.math_found == 'true' + run: exit 1 diff --git a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java index fcc4d775d43..bb4482a192a 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java @@ -1,6 +1,7 @@ package org.tron.core.actuator; import static java.util.stream.Collectors.toList; +import static org.tron.common.math.StrictMathWrapper.addExact; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -111,7 +112,7 @@ private boolean checkPermission(Permission permission) throws ContractValidateEx throw new ContractValidateException("key's weight should be greater than 0"); } try { - weightSum = Math.addExact(weightSum, key.getWeight()); + weightSum = addExact(weightSum, key.getWeight()); } catch (ArithmeticException e) { throw new ContractValidateException(e.getMessage()); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java index 7848f898ced..70675a8f0b0 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.floorDiv; +import static org.tron.common.math.StrictMathWrapper.multiplyExact; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; @@ -24,7 +26,6 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.ExchangeStore; import org.tron.core.store.ExchangeV2Store; -import org.tron.core.utils.TransactionUtil; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; @@ -71,14 +72,14 @@ public boolean execute(Object object) throws ContractExeException { if (Arrays.equals(tokenID, firstTokenID)) { anotherTokenID = secondTokenID; - anotherTokenQuant = Math - .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); + anotherTokenQuant = floorDiv(multiplyExact( + secondTokenBalance, tokenQuant), firstTokenBalance); exchangeCapsule.setBalance(firstTokenBalance + tokenQuant, secondTokenBalance + anotherTokenQuant); } else { anotherTokenID = firstTokenID; - anotherTokenQuant = Math - .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); + anotherTokenQuant = floorDiv(multiplyExact( + firstTokenBalance, tokenQuant), secondTokenBalance); exchangeCapsule.setBalance(firstTokenBalance + anotherTokenQuant, secondTokenBalance + tokenQuant); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java index 8929305d68c..fb8fe9384d3 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java @@ -76,16 +76,12 @@ public boolean execute(Object object) throws ContractExeException { BigInteger bigTokenQuant = new BigInteger(String.valueOf(tokenQuant)); if (Arrays.equals(tokenID, firstTokenID)) { anotherTokenID = secondTokenID; -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant) .divide(bigFirstTokenBalance).longValueExact(); exchangeCapsule.setBalance(firstTokenBalance - tokenQuant, secondTokenBalance - anotherTokenQuant); } else { anotherTokenID = firstTokenID; -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant) .divide(bigSecondTokenBalance).longValueExact(); exchangeCapsule.setBalance(firstTokenBalance - anotherTokenQuant, @@ -210,8 +206,6 @@ public boolean validate() throws ContractValidateException { BigDecimal bigSecondTokenBalance = new BigDecimal(String.valueOf(secondTokenBalance)); BigDecimal bigTokenQuant = new BigDecimal(String.valueOf(tokenQuant)); if (Arrays.equals(tokenID, firstTokenID)) { -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant) .divideToIntegralValue(bigFirstTokenBalance).longValueExact(); if (firstTokenBalance < tokenQuant || secondTokenBalance < anotherTokenQuant) { @@ -230,8 +224,6 @@ public boolean validate() throws ContractValidateException { } } else { -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant) .divideToIntegralValue(bigSecondTokenBalance).longValueExact(); if (secondTokenBalance < tokenQuant || firstTokenBalance < anotherTokenQuant) { diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index 15e5a98f86a..7402a313c8e 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -15,6 +15,8 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.subtractExact; import static org.tron.core.actuator.ActuatorConstant.CONTRACT_NOT_EXIST; import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; import static org.tron.core.actuator.ActuatorConstant.TX_RESULT_NULL; @@ -244,7 +246,7 @@ public boolean validate() throws ContractValidateException { long fee = calcFee(); if (Arrays.equals(sellTokenID, "_".getBytes())) { - if (ownerAccount.getBalance() < Math.addExact(sellTokenQuantity, fee)) { + if (ownerAccount.getBalance() < addExact(sellTokenQuantity, fee)) { throw new ContractValidateException("No enough balance !"); } } else { @@ -447,7 +449,7 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, takerOrderCapsule.setSellTokenQuantityRemain(0); MarketUtils.updateOrderState(takerOrderCapsule, State.INACTIVE, marketAccountStore); - makerOrderCapsule.setSellTokenQuantityRemain(Math.subtractExact( + makerOrderCapsule.setSellTokenQuantityRemain(subtractExact( makerOrderCapsule.getSellTokenQuantityRemain(), takerBuyTokenQuantityRemain)); } else { // taker > maker @@ -475,7 +477,7 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, return; } else { makerOrderCapsule.setSellTokenQuantityRemain(0); - takerOrderCapsule.setSellTokenQuantityRemain(Math.subtractExact( + takerOrderCapsule.setSellTokenQuantityRemain(subtractExact( takerOrderCapsule.getSellTokenQuantityRemain(), makerBuyTokenQuantityReceive)); } } @@ -524,7 +526,8 @@ private MarketOrderCapsule createAndSaveOrder(AccountCapsule accountCapsule, private void transferBalanceOrToken(AccountCapsule accountCapsule) { if (Arrays.equals(sellTokenID, "_".getBytes())) { - accountCapsule.setBalance(Math.subtractExact(accountCapsule.getBalance(), sellTokenQuantity)); + accountCapsule.setBalance(subtractExact( + accountCapsule.getBalance(), sellTokenQuantity)); } else { accountCapsule .reduceAssetAmountV2(sellTokenID, sellTokenQuantity, dynamicStore, assetIssueStore); @@ -537,7 +540,7 @@ private void addTrxOrToken(MarketOrderCapsule orderCapsule, long num, byte[] buyTokenId = orderCapsule.getBuyTokenId(); if (Arrays.equals(buyTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact(accountCapsule.getBalance(), num)); + accountCapsule.setBalance(addExact(accountCapsule.getBalance(), num)); } else { accountCapsule .addAssetAmountV2(buyTokenId, num, dynamicStore, assetIssueStore); @@ -550,7 +553,7 @@ private void addTrxOrToken(MarketOrderCapsule orderCapsule, long num) { byte[] buyTokenId = orderCapsule.getBuyTokenId(); if (Arrays.equals(buyTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact(accountCapsule.getBalance(), num)); + accountCapsule.setBalance(addExact(accountCapsule.getBalance(), num)); } else { accountCapsule .addAssetAmountV2(buyTokenId, num, dynamicStore, assetIssueStore); diff --git a/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java b/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java index 77e345b2a92..9156f4dbbd8 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java @@ -15,6 +15,11 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.floorDiv; +import static org.tron.common.math.StrictMathWrapper.multiplyExact; +import static org.tron.common.math.StrictMathWrapper.subtractExact; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; @@ -64,8 +69,8 @@ public boolean execute(Object object) throws ContractExeException { //subtract from owner address byte[] ownerAddress = participateAssetIssueContract.getOwnerAddress().toByteArray(); AccountCapsule ownerAccount = accountStore.get(ownerAddress); - long balance = Math.subtractExact(ownerAccount.getBalance(), cost); - balance = Math.subtractExact(balance, fee); + long balance = subtractExact(ownerAccount.getBalance(), cost); + balance = subtractExact(balance, fee); ownerAccount.setBalance(balance); byte[] key = participateAssetIssueContract.getAssetName().toByteArray(); @@ -74,14 +79,14 @@ public boolean execute(Object object) throws ContractExeException { assetIssueCapsule = Commons .getAssetIssueStoreFinal(dynamicStore, assetIssueStore, assetIssueV2Store).get(key); - long exchangeAmount = Math.multiplyExact(cost, assetIssueCapsule.getNum()); - exchangeAmount = Math.floorDiv(exchangeAmount, assetIssueCapsule.getTrxNum()); + long exchangeAmount = multiplyExact(cost, assetIssueCapsule.getNum()); + exchangeAmount = floorDiv(exchangeAmount, assetIssueCapsule.getTrxNum()); ownerAccount.addAssetAmountV2(key, exchangeAmount, dynamicStore, assetIssueStore); //add to to_address byte[] toAddress = participateAssetIssueContract.getToAddress().toByteArray(); AccountCapsule toAccount = accountStore.get(toAddress); - toAccount.setBalance(Math.addExact(toAccount.getBalance(), cost)); + toAccount.setBalance(addExact(toAccount.getBalance(), cost)); if (!toAccount.reduceAssetAmountV2(key, exchangeAmount, dynamicStore, assetIssueStore)) { throw new ContractExeException("reduceAssetAmount failed !"); } @@ -156,7 +161,7 @@ public boolean validate() throws ContractValidateException { try { //Whether the balance is enough long fee = calcFee(); - if (ownerAccount.getBalance() < Math.addExact(amount, fee)) { + if (ownerAccount.getBalance() < addExact(amount, fee)) { throw new ContractValidateException("No enough balance !"); } @@ -181,8 +186,8 @@ public boolean validate() throws ContractValidateException { int trxNum = assetIssueCapsule.getTrxNum(); int num = assetIssueCapsule.getNum(); - long exchangeAmount = Math.multiplyExact(amount, num); - exchangeAmount = Math.floorDiv(exchangeAmount, trxNum); + long exchangeAmount = multiplyExact(amount, num); + exchangeAmount = floorDiv(exchangeAmount, trxNum); if (exchangeAmount <= 0) { throw new ContractValidateException("Can not process the exchange!"); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java index 284650f1ffb..c0f065274a6 100644 --- a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.subtractExact; import static org.tron.core.capsule.TransactionCapsule.getShieldTransactionHashIgnoreTypeException; import static org.tron.core.utils.ZenChainParams.ZC_ENCCIPHERTEXT_SIZE; import static org.tron.core.utils.ZenChainParams.ZC_OUTCIPHERTEXT_SIZE; @@ -96,9 +98,9 @@ public boolean execute(Object result) //adjust and verify total shielded pool value try { - Commons.adjustTotalShieldedPoolValue( - Math.addExact(Math.subtractExact(shieldedTransferContract.getToAmount(), - shieldedTransferContract.getFromAmount()), fee), dynamicStore); + Commons.adjustTotalShieldedPoolValue(addExact(subtractExact( + shieldedTransferContract.getToAmount(), + shieldedTransferContract.getFromAmount()), fee), dynamicStore); } catch (ArithmeticException | BalanceInsufficientException e) { logger.debug(e.getMessage(), e); ret.setStatus(0, code.FAILED); @@ -327,9 +329,11 @@ private void checkProof(List spendDescriptions, long totalShieldedPoolValue = dynamicStore .getTotalShieldedPoolValue(); try { - valueBalance = Math.addExact(Math.subtractExact(shieldedTransferContract.getToAmount(), + valueBalance = addExact(subtractExact( + shieldedTransferContract.getToAmount(), shieldedTransferContract.getFromAmount()), fee); - totalShieldedPoolValue = Math.subtractExact(totalShieldedPoolValue, valueBalance); + totalShieldedPoolValue = subtractExact( + totalShieldedPoolValue, valueBalance); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ZkProofValidateException(e.getMessage(), true); @@ -452,7 +456,7 @@ private void validateTransparent(ShieldedTransferContract shieldedTransferContra AccountCapsule toAccount = accountStore.get(toAddress); if (toAccount != null) { try { - Math.addExact(getZenBalance(toAccount), toAmount); + addExact(getZenBalance(toAccount), toAmount); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java index 5e3d605aed7..2674356063a 100755 --- a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.addExact; import static org.tron.core.config.Parameter.ChainConstant.TRANSFER_FEE; import com.google.protobuf.ByteString; @@ -58,7 +59,7 @@ public boolean execute(Object object) throws ContractExeException { fee = fee + dynamicStore.getCreateNewAccountFeeInSystemContract(); } - Commons.adjustBalance(accountStore, ownerAddress, -(Math.addExact(fee, amount))); + Commons.adjustBalance(accountStore, ownerAddress, -(addExact(fee, amount))); if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { @@ -156,7 +157,7 @@ public boolean validate() throws ContractValidateException { } } - if (balance < Math.addExact(amount, fee)) { + if (balance < addExact(amount, fee)) { logger.warn("Balance is not sufficient. Account: {}, balance: {}, amount: {}, fee: {}.", StringUtil.encode58Check(ownerAddress), balance, amount, fee); throw new ContractValidateException( @@ -164,7 +165,7 @@ public boolean validate() throws ContractValidateException { } if (toAccount != null) { - Math.addExact(toAccount.getBalance(), amount); + addExact(toAccount.getBalance(), amount); } } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java index de2b2faec86..8d3b6ef2005 100644 --- a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java @@ -15,6 +15,8 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.addExact; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; @@ -177,7 +179,7 @@ public boolean validate() throws ContractValidateException { assetBalance = toAccount.getAsset(dynamicStore, ByteArray.toStr(assetName)); if (assetBalance != null) { try { - assetBalance = Math.addExact(assetBalance, amount); //check if overflow + assetBalance = addExact(assetBalance, amount); //check if overflow } catch (Exception e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); diff --git a/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java index 79a09664180..d3a6e879136 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; @@ -82,7 +83,7 @@ public boolean execute(Object result) throws ContractExeException { * ((double) (dynamicStore.getTotalNetLimit()) / dynamicStore.getTotalNetWeight())); transferUsage = (long) (receiverCapsule.getNetUsage() * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForBandwidth())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); + transferUsage = min(unDelegateMaxUsage, transferUsage); receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); } @@ -105,7 +106,7 @@ public boolean execute(Object result) throws ContractExeException { * ((double) (dynamicStore.getTotalEnergyCurrentLimit()) / dynamicStore.getTotalEnergyWeight())); transferUsage = (long) (receiverCapsule.getEnergyUsage() * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForEnergy())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); + transferUsage = min(unDelegateMaxUsage, transferUsage); receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); } 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 08d0f5a8da5..5938d46fe6c 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -1,9 +1,11 @@ package org.tron.core.actuator; -import static java.lang.Math.max; -import static java.lang.Math.min; import static org.apache.commons.lang3.ArrayUtils.getLength; import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.floorDiv; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.ByteString; @@ -124,7 +126,7 @@ public void validate(Object object) throws ContractValidateException { trx = context.getTrxCap().getInstance(); // If tx`s fee limit is set, use it to calc max energy limit for constant call if (isConstantCall && trx.getRawData().getFeeLimit() > 0) { - maxEnergyLimit = Math.min(maxEnergyLimit, trx.getRawData().getFeeLimit() + maxEnergyLimit = min(maxEnergyLimit, trx.getRawData().getFeeLimit() / context.getStoreFactory().getChainBaseManager() .getDynamicPropertiesStore().getEnergyFee()); } @@ -564,7 +566,7 @@ public long getAccountEnergyLimitWithFixRatio(AccountCapsule account, long feeLi } long energyFromBalance = max(account.getBalance() - callValue, 0) / sunPerEnergy; - long availableEnergy = Math.addExact(leftFrozenEnergy, energyFromBalance); + long availableEnergy = addExact(leftFrozenEnergy, energyFromBalance); long energyFromFeeLimit = feeLimit / sunPerEnergy; if (VMConfig.allowTvmFreezeV2()) { @@ -599,8 +601,8 @@ private long getAccountEnergyLimitWithFloatRatio(AccountCapsule account, long fe // can change the calc way long leftEnergyFromFreeze = rootRepository.getAccountLeftEnergyFromFreeze(account); callValue = max(callValue, 0); - long energyFromBalance = Math - .floorDiv(max(account.getBalance() - callValue, 0), sunPerEnergy); + long energyFromBalance = floorDiv(max( + account.getBalance() - callValue, 0), sunPerEnergy); long energyFromFeeLimit; long totalBalanceForEnergyFreeze = account.getAllFrozenBalanceForEnergy(); @@ -619,13 +621,12 @@ private long getAccountEnergyLimitWithFloatRatio(AccountCapsule account, long fe .multiply(BigInteger.valueOf(feeLimit)) .divide(BigInteger.valueOf(totalBalanceForEnergyFreeze)).longValueExact(); } else { - energyFromFeeLimit = Math - .addExact(leftEnergyFromFreeze, - (feeLimit - leftBalanceForEnergyFreeze) / sunPerEnergy); + energyFromFeeLimit = addExact( + leftEnergyFromFreeze, (feeLimit - leftBalanceForEnergyFreeze) / sunPerEnergy); } } - return min(Math.addExact(leftEnergyFromFreeze, energyFromBalance), energyFromFeeLimit); + return min(addExact(leftEnergyFromFreeze, energyFromBalance), energyFromFeeLimit); } public long getTotalEnergyLimit(AccountCapsule creator, AccountCapsule caller, @@ -748,7 +749,7 @@ public long getTotalEnergyLimitWithFixRatio(AccountCapsule creator, AccountCapsu receipt.setOriginEnergyMergedWindowSize(creator.getWindowSize(ENERGY)); rootRepository.updateAccount(creator.createDbKey(), creator); } - return Math.addExact(callerEnergyLimit, creatorEnergyLimit); + return addExact(callerEnergyLimit, creatorEnergyLimit); } private long getTotalEnergyLimitWithFloatRatio(AccountCapsule creator, AccountCapsule caller, @@ -768,9 +769,10 @@ private long getTotalEnergyLimitWithFloatRatio(AccountCapsule creator, AccountCa if (creatorEnergyLimit * consumeUserResourcePercent > (VMConstant.ONE_HUNDRED - consumeUserResourcePercent) * callerEnergyLimit) { - return Math.floorDiv(callerEnergyLimit * VMConstant.ONE_HUNDRED, consumeUserResourcePercent); + return floorDiv( + callerEnergyLimit * VMConstant.ONE_HUNDRED, consumeUserResourcePercent); } else { - return Math.addExact(callerEnergyLimit, creatorEnergyLimit); + return addExact(callerEnergyLimit, creatorEnergyLimit); } } diff --git a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index 7044564b1e1..6a6ca550abc 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -16,6 +16,7 @@ package org.tron.core.utils; import static org.tron.common.crypto.Hash.sha3omit12; +import static org.tron.common.math.StrictMathWrapper.max; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -39,7 +40,6 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; import org.tron.core.ChainBaseManager; -import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.exception.PermissionException; @@ -50,10 +50,9 @@ import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract; import org.tron.protos.Protocol.Transaction.Result.contractResult; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.BalanceContract.DelegateResourceContract; @Slf4j(topic = "capsule") @Component @@ -270,7 +269,7 @@ public static long estimateConsumeBandWidthSize(DynamicPropertiesStore dps, long DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() .setBalance(TRX_PRECISION); long builder2Size = builder2.build().getSerializedSize(); - long addSize = Math.max(builderSize - builder2Size, 0L); + long addSize = max(builderSize - builder2Size, 0L); return DELEGATE_COST_BASE_SIZE + addSize; } diff --git a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java index 79d08af1aad..182367dfa11 100644 --- a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java +++ b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java @@ -1,6 +1,8 @@ package org.tron.core.vm; import static java.util.Arrays.copyOfRange; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.common.runtime.vm.DataWord.WORD_SIZE; import static org.tron.common.utils.BIUtil.addSafely; import static org.tron.common.utils.BIUtil.isLessThan; @@ -16,7 +18,6 @@ import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import com.google.protobuf.ByteString; - import java.lang.reflect.Constructor; import java.math.BigInteger; import java.security.MessageDigest; @@ -624,14 +625,14 @@ public long getEnergyForData(byte[] data) { int expLen = parseLen(data, 1); int modLen = parseLen(data, 2); - byte[] expHighBytes = parseBytes(data, addSafely(ARGS_OFFSET, baseLen), Math.min(expLen, 32)); + byte[] expHighBytes = parseBytes(data, addSafely(ARGS_OFFSET, baseLen), min(expLen, 32)); - long multComplexity = getMultComplexity(Math.max(baseLen, modLen)); + long multComplexity = getMultComplexity(max(baseLen, modLen)); long adjExpLen = getAdjustedExponentLength(expHighBytes, expLen); // use big numbers to stay safe in case of overflow BigInteger energy = BigInteger.valueOf(multComplexity) - .multiply(BigInteger.valueOf(Math.max(adjExpLen, 1))) + .multiply(BigInteger.valueOf(max(adjExpLen, 1))) .divide(GQUAD_DIVISOR); return isLessThan(energy, BigInteger.valueOf(Long.MAX_VALUE)) ? energy.longValueExact() diff --git a/actuator/src/main/java/org/tron/core/vm/VMUtils.java b/actuator/src/main/java/org/tron/core/vm/VMUtils.java index 1df0e0e22f1..7adc8e66df5 100644 --- a/actuator/src/main/java/org/tron/core/vm/VMUtils.java +++ b/actuator/src/main/java/org/tron/core/vm/VMUtils.java @@ -2,6 +2,7 @@ import static java.lang.String.format; import static org.apache.commons.codec.binary.Base64.encodeBase64String; +import static org.tron.common.math.StrictMathWrapper.addExact; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -169,7 +170,7 @@ public static boolean validateForSmartContract(Repository deposit, byte[] ownerA "Validate InternalTransfer error, balance is not sufficient."); } - Math.addExact(toAccount.getBalance(), amount); + addExact(toAccount.getBalance(), amount); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); @@ -230,7 +231,7 @@ public static boolean validateForSmartContract(Repository deposit, byte[] ownerA ByteArray.toStr(tokenIdWithoutLeadingZero)); if (assetBalance != null) { try { - assetBalance = Math.addExact(assetBalance, amount); //check if overflow + assetBalance = addExact(assetBalance, amount); //check if overflow } catch (Exception e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java index d521e596e3e..62ade7fbc1e 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java @@ -1,5 +1,6 @@ package org.tron.core.vm.nativecontract; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -115,7 +116,7 @@ public void execute(UnDelegateResourceParam param, Repository repo) { * dynamicStore.getTotalNetLimit() / repo.getTotalNetWeight()); transferUsage = (long) (receiverCapsule.getNetUsage() * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForBandwidth())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); + transferUsage = min(unDelegateMaxUsage, transferUsage); receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); } @@ -139,7 +140,7 @@ public void execute(UnDelegateResourceParam param, Repository repo) { * dynamicStore.getTotalEnergyCurrentLimit() / repo.getTotalEnergyWeight()); transferUsage = (long) (receiverCapsule.getEnergyUsage() * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForEnergy())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); + transferUsage = min(unDelegateMaxUsage, transferUsage); receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); } diff --git a/actuator/src/main/java/org/tron/core/vm/program/Memory.java b/actuator/src/main/java/org/tron/core/vm/program/Memory.java index e5cbebad2b9..50b3d3c0c46 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Memory.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Memory.java @@ -1,8 +1,9 @@ package org.tron.core.vm.program; -import static java.lang.Math.ceil; -import static java.lang.Math.min; import static java.lang.String.format; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.ceilAsInt; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.common.utils.ByteUtil.EMPTY_BYTE_ARRAY; import static org.tron.common.utils.ByteUtil.oneByteToHexString; @@ -104,16 +105,16 @@ public void extend(int address, int size) { return; } - final int newSize = Math.addExact(address, size); + final int newSize = addExact(address, size); int toAllocate = newSize - internalSize(); if (toAllocate > 0) { - addChunks((int) ceil((double) toAllocate / CHUNK_SIZE)); + addChunks(ceilAsInt((double) toAllocate / CHUNK_SIZE)); } toAllocate = newSize - softSize; if (toAllocate > 0) { - toAllocate = (int) ceil((double) toAllocate / WORD_SIZE) * WORD_SIZE; - softSize = Math.addExact(softSize, toAllocate); + toAllocate = ceilAsInt((double) toAllocate / WORD_SIZE) * WORD_SIZE; + softSize = addExact(softSize, toAllocate); if (programListener != null) { programListener.onMemoryExtend(toAllocate); 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 4273778a7d6..79c2665ddaa 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 @@ -1,12 +1,15 @@ package org.tron.core.vm.program; -import static java.lang.StrictMath.min; import static java.lang.String.format; import static org.apache.commons.lang3.ArrayUtils.EMPTY_BYTE_ARRAY; import static org.apache.commons.lang3.ArrayUtils.getLength; import static org.apache.commons.lang3.ArrayUtils.isEmpty; import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; import static org.apache.commons.lang3.ArrayUtils.nullToEmpty; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; +import static org.tron.common.math.StrictMathWrapper.multiplyExact; import static org.tron.common.utils.ByteUtil.stripLeadingZeroes; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; @@ -629,7 +632,7 @@ private void withdrawRewardAndCancelVote(byte[] owner, Repository repo) { long balance = ownerCapsule.getBalance(); long allowance = ownerCapsule.getAllowance(); ownerCapsule.setInstance(ownerCapsule.getInstance().toBuilder() - .setBalance(Math.addExact(balance, allowance)) + .setBalance(addExact(balance, allowance)) .setAllowance(0) .setLatestWithdrawTime(getTimestamp().longValue() * 1000) .build()); @@ -1227,7 +1230,7 @@ public DataWord getContractAddress() { public DataWord getBlockHash(int index) { if (index < this.getNumber().longValue() - && index >= Math.max(256, this.getNumber().longValue()) - 256) { + && index >= max(256, this.getNumber().longValue()) - 256) { BlockCapsule blockCapsule = contractState.getBlockByNum(index); @@ -2152,10 +2155,12 @@ public boolean voteWitness(int witnessArrayOffset, int witnessArrayLength, VoteWitnessParam param = new VoteWitnessParam(); param.setVoterAddress(owner); - byte[] witnessArrayData = memoryChunk(Math.addExact(witnessArrayOffset, DataWord.WORD_SIZE), - Math.multiplyExact(witnessArrayLength, DataWord.WORD_SIZE)); - byte[] amountArrayData = memoryChunk(Math.addExact(amountArrayOffset, DataWord.WORD_SIZE), - Math.multiplyExact(amountArrayLength, DataWord.WORD_SIZE)); + byte[] witnessArrayData = memoryChunk( + addExact(witnessArrayOffset, DataWord.WORD_SIZE), + multiplyExact(witnessArrayLength, DataWord.WORD_SIZE)); + byte[] amountArrayData = memoryChunk( + addExact(amountArrayOffset, DataWord.WORD_SIZE), + multiplyExact(amountArrayLength, DataWord.WORD_SIZE)); for (int i = 0; i < witnessArrayLength; i++) { DataWord witness = new DataWord(Arrays.copyOfRange(witnessArrayData, 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 50fa5385c23..23ba39c249b 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 @@ -1,6 +1,8 @@ package org.tron.core.vm.repository; -import static java.lang.Long.max; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.round; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -681,7 +683,7 @@ public long addBalance(byte[] address, long value) { StringUtil.createReadableString(accountCapsule.createDbKey()) + " insufficient balance"); } - accountCapsule.setBalance(Math.addExact(balance, value)); + accountCapsule.setBalance(addExact(balance, value)); Key key = Key.create(address); accountCache.put(key, Value.create(accountCapsule, accountCache.get(key).getType().addType(Type.DIRTY))); @@ -841,7 +843,7 @@ private long increase(long lastUsage, long usage, long lastTime, long now, long if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay); } else { averageLastUsage = 0; } diff --git a/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java index 7bc760f9edf..8e831ad2361 100644 --- a/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java +++ b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java @@ -1,8 +1,10 @@ package org.tron.core.vm.utils; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; + import java.util.List; import java.util.stream.Collectors; - import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.tron.core.actuator.UnfreezeBalanceV2Actuator; @@ -162,7 +164,7 @@ public static long queryDelegatableResource(byte[] address, long type, Repositor } long v2NetUsage = getV2NetUsage(accountCapsule, usage); - return Math.max(0L, frozenV2Resource - v2NetUsage); + return max(0L, frozenV2Resource - v2NetUsage); } if (type == 1) { @@ -182,7 +184,7 @@ public static long queryDelegatableResource(byte[] address, long type, Repositor } long v2EnergyUsage = getV2EnergyUsage(accountCapsule, usage); - return Math.max(0L, frozenV2Resource - v2EnergyUsage); + return max(0L, frozenV2Resource - v2EnergyUsage); } return 0L; @@ -218,7 +220,7 @@ public static Triple checkUndelegateResource(byte[] address, l return Triple.of(0L, 0L, 0L); } - amount = Math.min(amount, resourceLimit); + amount = min(amount, resourceLimit); if (resourceLimit <= usagePair.getLeft()) { return Triple.of(0L, amount, usagePair.getRight()); } @@ -243,7 +245,7 @@ public static long getV2NetUsage(AccountCapsule ownerCapsule, long netUsage) { - ownerCapsule.getFrozenBalance() - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); - return Math.max(0, v2NetUsage); + return max(0, v2NetUsage); } public static long getV2EnergyUsage(AccountCapsule ownerCapsule, long energyUsage) { @@ -251,7 +253,7 @@ public static long getV2EnergyUsage(AccountCapsule ownerCapsule, long energyUsag - ownerCapsule.getEnergyFrozenBalance() - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); - return Math.max(0, v2EnergyUsage); + return max(0, v2EnergyUsage); } } diff --git a/chainbase/src/main/java/org/tron/common/utils/Commons.java b/chainbase/src/main/java/org/tron/common/utils/Commons.java index 55542d494b4..cc15b17e777 100644 --- a/chainbase/src/main/java/org/tron/common/utils/Commons.java +++ b/chainbase/src/main/java/org/tron/common/utils/Commons.java @@ -1,5 +1,8 @@ package org.tron.common.utils; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.subtractExact; + import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.tron.common.parameter.CommonParameter; @@ -77,7 +80,7 @@ public static void adjustBalance(AccountStore accountStore, AccountCapsule accou String.format("%s insufficient balance, balance: %d, amount: %d", StringUtil.createReadableString(account.createDbKey()), balance, -amount)); } - account.setBalance(Math.addExact(balance, amount)); + account.setBalance(addExact(balance, amount)); accountStore.put(account.getAddress().toByteArray(), account); } @@ -137,8 +140,8 @@ public static void adjustAssetBalanceV2(AccountCapsule account, String AssetID, public static void adjustTotalShieldedPoolValue(long valueBalance, DynamicPropertiesStore dynamicPropertiesStore) throws BalanceInsufficientException { - long totalShieldedPoolValue = Math - .subtractExact(dynamicPropertiesStore.getTotalShieldedPoolValue(), valueBalance); + long totalShieldedPoolValue = subtractExact( + dynamicPropertiesStore.getTotalShieldedPoolValue(), valueBalance); if (totalShieldedPoolValue < 0) { throw new BalanceInsufficientException(String.format( "total shielded pool value can not below 0, actual: %d", totalShieldedPoolValue)); diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index 7cbac28e781..ca04bbc9713 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -1,5 +1,6 @@ package org.tron.common.utils; +import static org.tron.common.math.StrictMathWrapper.ceilAsInt; import static org.tron.common.utils.StringUtil.encode58Check; import com.google.common.collect.Maps; @@ -98,8 +99,7 @@ private boolean passNew(int version) { ++count; } } - return count >= Math - .ceil((double) versionEnum.getHardForkRate() * stats.length / 100); + return count >= ceilAsInt((double) versionEnum.getHardForkRate() * stats.length / 100); } 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 b60fed63cda..5c3aac8bda7 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -15,9 +15,23 @@ package org.tron.core.capsule; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.subtractExact; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; + import com.google.common.collect.Maps; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import java.util.List; +import java.util.Map; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.tron.common.utils.ByteArray; @@ -27,8 +41,8 @@ import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Account.AccountResource; import org.tron.protos.Protocol.Account.Builder; -import org.tron.protos.Protocol.Account.Frozen; import org.tron.protos.Protocol.Account.FreezeV2; +import org.tron.protos.Protocol.Account.Frozen; import org.tron.protos.Protocol.Account.UnFreezeV2; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Key; @@ -38,19 +52,6 @@ import org.tron.protos.contract.AccountContract.AccountCreateContract; import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static java.lang.Math.ceil; -import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; -import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; -import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; -import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; -import static org.tron.protos.contract.Common.ResourceCode.ENERGY; -import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; -import static org.tron.protos.contract.Common.ResourceCode; - @Slf4j(topic = "capsule") public class AccountCapsule implements ProtoCapsule, Comparable { @@ -403,13 +404,13 @@ public void addAcquiredDelegatedFrozenV2BalanceForBandwidth(long balance) { public void safeAddAcquiredDelegatedFrozenBalanceForBandwidth(long balance) { this.account = this.account.toBuilder().setAcquiredDelegatedFrozenBalanceForBandwidth( - Math.max(0, this.account.getAcquiredDelegatedFrozenBalanceForBandwidth() + balance)) + max(0, this.account.getAcquiredDelegatedFrozenBalanceForBandwidth() + balance)) .build(); } public void safeAddAcquiredDelegatedFrozenV2BalanceForBandwidth(long balance) { this.account = this.account.toBuilder().setAcquiredDelegatedFrozenV2BalanceForBandwidth( - Math.max(0, this.account.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + balance)) + max(0, this.account.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + balance)) .build(); } @@ -499,7 +500,7 @@ public void addAcquiredDelegatedFrozenV2BalanceForEnergy(long balance) { public void safeAddAcquiredDelegatedFrozenBalanceForEnergy(long balance) { AccountResource newAccountResource = getAccountResource().toBuilder() .setAcquiredDelegatedFrozenBalanceForEnergy( - Math.max(0, getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy() + balance)) + max(0, getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy() + balance)) .build(); this.account = this.account.toBuilder() @@ -509,7 +510,7 @@ public void safeAddAcquiredDelegatedFrozenBalanceForEnergy(long balance) { public void safeAddAcquiredDelegatedFrozenV2BalanceForEnergy(long balance) { AccountResource newAccountResource = getAccountResource().toBuilder() - .setAcquiredDelegatedFrozenV2BalanceForEnergy(Math.max(0, getAccountResource() + .setAcquiredDelegatedFrozenV2BalanceForEnergy(max(0, getAccountResource() .getAcquiredDelegatedFrozenV2BalanceForEnergy() + balance)).build(); this.account = this.account.toBuilder().setAccountResource(newAccountResource).build(); } @@ -718,7 +719,7 @@ public boolean addAssetAmount(byte[] key, long amount) { if (currentAmount == null) { currentAmount = 0L; } - this.account = this.account.toBuilder().putAsset(nameKey, Math.addExact(currentAmount, amount)) + this.account = this.account.toBuilder().putAsset(nameKey, addExact(currentAmount, amount)) .build(); return true; } @@ -737,8 +738,8 @@ public boolean addAssetAmountV2(byte[] key, long amount, currentAmount = 0L; } this.account = this.account.toBuilder() - .putAsset(nameKey, Math.addExact(currentAmount, amount)) - .putAssetV2(tokenID, Math.addExact(currentAmount, amount)) + .putAsset(nameKey, addExact(currentAmount, amount)) + .putAssetV2(tokenID, addExact(currentAmount, amount)) .build(); } //key is token id @@ -750,7 +751,7 @@ public boolean addAssetAmountV2(byte[] key, long amount, currentAmount = 0L; } this.account = this.account.toBuilder() - .putAssetV2(tokenIDStr, Math.addExact(currentAmount, amount)) + .putAssetV2(tokenIDStr, addExact(currentAmount, amount)) .build(); } return true; @@ -762,7 +763,7 @@ public boolean reduceAssetAmount(byte[] key, long amount) { Long currentAmount = assetMap.get(nameKey); if (amount > 0 && null != currentAmount && amount <= currentAmount) { this.account = this.account.toBuilder() - .putAsset(nameKey, Math.subtractExact(currentAmount, amount)).build(); + .putAsset(nameKey, subtractExact(currentAmount, amount)).build(); return true; } @@ -781,8 +782,8 @@ public boolean reduceAssetAmountV2(byte[] key, long amount, Long currentAmount = assetMap.get(nameKey); if (amount > 0 && null != currentAmount && amount <= currentAmount) { this.account = this.account.toBuilder() - .putAsset(nameKey, Math.subtractExact(currentAmount, amount)) - .putAssetV2(tokenID, Math.subtractExact(currentAmount, amount)) + .putAsset(nameKey, subtractExact(currentAmount, amount)) + .putAssetV2(tokenID, subtractExact(currentAmount, amount)) .build(); return true; } @@ -794,7 +795,7 @@ public boolean reduceAssetAmountV2(byte[] key, long amount, Long currentAmount = assetMapV2.get(tokenID); if (amount > 0 && null != currentAmount && amount <= currentAmount) { this.account = this.account.toBuilder() - .putAssetV2(tokenID, Math.subtractExact(currentAmount, amount)) + .putAssetV2(tokenID, subtractExact(currentAmount, amount)) .build(); return true; } diff --git a/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java index cb6292ed290..d6a038d62f9 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java @@ -15,8 +15,8 @@ package org.tron.core.capsule; -import static java.lang.Math.max; -import static java.lang.Math.min; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import com.google.protobuf.Any; import com.google.protobuf.ByteString; @@ -28,7 +28,6 @@ import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper; -import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapperOrBuilder; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; @Slf4j(topic = "capsule") diff --git a/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java index 8ebb86ea332..4bd7753367b 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java @@ -1,5 +1,7 @@ package org.tron.core.capsule; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.Constant.DYNAMIC_ENERGY_DECREASE_DIVISION; import static org.tron.core.Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; @@ -108,7 +110,7 @@ public boolean catchUpToCycle( double increasePercent = 1 + (double) increaseFactor / precisionFactor; this.contractState = ContractState.newBuilder() .setUpdateCycle(lastCycle) - .setEnergyFactor(Math.min( + .setEnergyFactor(min( maxFactor, (long) ((getEnergyFactor() + precisionFactor) * increasePercent) - precisionFactor)) .build(); @@ -132,7 +134,7 @@ public boolean catchUpToCycle( // That means we merge this special case to normal cases) this.contractState = ContractState.newBuilder() .setUpdateCycle(newCycle) - .setEnergyFactor(Math.max( + .setEnergyFactor(max( 0, (long) ((getEnergyFactor() + precisionFactor) * decreasePercent) - precisionFactor)) .build(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java index 7d003b6b0e4..8e2faefda9b 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java @@ -1,5 +1,8 @@ package org.tron.core.capsule; +import static org.tron.common.math.StrictMathWrapper.min; +import static org.tron.common.math.StrictMathWrapper.multiplyExact; + import java.util.Objects; import lombok.Getter; import lombok.Setter; @@ -220,7 +223,7 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, payEnergyBill(dynamicPropertiesStore, accountStore, forkController, caller, receipt.getEnergyUsageTotal(), receipt.getResult(), energyProcessor, now); } else { - long originUsage = Math.multiplyExact(receipt.getEnergyUsageTotal(), percent) / 100; + long originUsage = multiplyExact(receipt.getEnergyUsageTotal(), percent) / 100; originUsage = getOriginUsage(dynamicPropertiesStore, origin, originEnergyLimit, energyProcessor, originUsage); @@ -239,14 +242,14 @@ private long getOriginUsage(DynamicPropertiesStore dynamicPropertiesStore, Accou if (dynamicPropertiesStore.getAllowTvmFreeze() == 1 || dynamicPropertiesStore.supportUnfreezeDelay()) { - return Math.min(originUsage, Math.min(originEnergyLeft, originEnergyLimit)); + return min(originUsage, min(originEnergyLeft, originEnergyLimit)); } if (checkForEnergyLimit(dynamicPropertiesStore)) { - return Math.min(originUsage, - Math.min(energyProcessor.getAccountLeftEnergyFromFreeze(origin), originEnergyLimit)); + return min(originUsage, + min(energyProcessor.getAccountLeftEnergyFromFreeze(origin), originEnergyLimit)); } - return Math.min(originUsage, energyProcessor.getAccountLeftEnergyFromFreeze(origin)); + return min(originUsage, energyProcessor.getAccountLeftEnergyFromFreeze(origin)); } private void payEnergyBill( diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java index f345a96df81..0c6cce5442a 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java @@ -15,6 +15,10 @@ package org.tron.core.capsule.utils; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.floorDiv; +import static org.tron.common.math.StrictMathWrapper.multiplyExact; + import com.google.protobuf.ByteString; import java.math.BigInteger; import java.util.Arrays; @@ -230,8 +234,8 @@ public static byte[] createPairKey(byte[] sellTokenId, byte[] buyTokenId) { public static int comparePrice(long price1SellQuantity, long price1BuyQuantity, long price2SellQuantity, long price2BuyQuantity) { try { - return Long.compare(Math.multiplyExact(price1BuyQuantity, price2SellQuantity), - Math.multiplyExact(price2BuyQuantity, price1SellQuantity)); + return Long.compare(multiplyExact(price1BuyQuantity, price2SellQuantity), + multiplyExact(price2BuyQuantity, price1SellQuantity)); } catch (ArithmeticException ex) { // do nothing here, because we will use BigInteger to compute again @@ -299,8 +303,8 @@ public static void updateOrderState(MarketOrderCapsule orderCapsule, public static long multiplyAndDivide(long a, long b, long c) { try { - long tmp = Math.multiplyExact(a, b); - return Math.floorDiv(tmp, c); + long tmp = multiplyExact(a, b); + return floorDiv(tmp, c); } catch (ArithmeticException ex) { // do nothing here, because we will use BigInteger to compute again } @@ -320,7 +324,7 @@ public static void returnSellTokenRemain(MarketOrderCapsule orderCapsule, byte[] sellTokenId = orderCapsule.getSellTokenId(); long sellTokenQuantityRemain = orderCapsule.getSellTokenQuantityRemain(); if (Arrays.equals(sellTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact( + accountCapsule.setBalance(addExact( accountCapsule.getBalance(), sellTokenQuantityRemain)); } else { accountCapsule diff --git a/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java b/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java index 5cd0f796374..9669fd7302d 100644 --- a/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java @@ -1,6 +1,7 @@ package org.tron.core.db; -import static java.lang.Long.max; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -79,8 +80,7 @@ public void updateAdaptiveTotalEnergyLimit() { // logger.info(totalEnergyAverageUsage + "<" + targetTotalEnergyLimit + "\n" + result); } - result = Math.min( - Math.max(result, totalEnergyLimit), + result = min(max(result, totalEnergyLimit), totalEnergyLimit * dynamicPropertiesStore.getAdaptiveResourceLimitMultiplier() ); diff --git a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java index c1875408850..969081cee96 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -1,5 +1,7 @@ package org.tron.core.db; +import static org.tron.common.math.StrictMathWrapper.min; +import static org.tron.common.math.StrictMathWrapper.round; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; @@ -51,7 +53,7 @@ protected long increase(long lastUsage, long usage, long lastTime, long now, lon if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay); } else { averageLastUsage = 0; } @@ -79,7 +81,7 @@ public long increase(AccountCapsule accountCapsule, ResourceCode resourceCode, if (lastTime + oldWindowSize > now) { long delta = now - lastTime; double decay = (oldWindowSize - delta) / (double) oldWindowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay); } else { averageLastUsage = 0; } @@ -111,7 +113,7 @@ public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, if (lastTime + oldWindowSize > now) { long delta = now - lastTime; double decay = (oldWindowSize - delta) / (double) oldWindowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay); } else { averageLastUsage = 0; } @@ -127,7 +129,7 @@ public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, long remainWindowSize = oldWindowSizeV2 - (now - lastTime) * WINDOW_SIZE_PRECISION; long newWindowSize = divideCeil( remainUsage * remainWindowSize + usage * this.windowSize * WINDOW_SIZE_PRECISION, newUsage); - newWindowSize = Math.min(newWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); + newWindowSize = min(newWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); accountCapsule.setNewWindowSizeV2(resourceCode, newWindowSize); return newUsage; } @@ -189,7 +191,7 @@ public void unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule rece divideCeil( ownerUsage * remainOwnerWindowSizeV2 + transferUsage * remainReceiverWindowSizeV2, newOwnerUsage); - newOwnerWindowSize = Math.min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); + newOwnerWindowSize = min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); owner.setNewWindowSizeV2(resourceCode, newOwnerWindowSize); owner.setUsage(resourceCode, newOwnerUsage); owner.setLatestTime(resourceCode, now); diff --git a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java index e9c4feb7e18..467a2cb3d65 100644 --- a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java +++ b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java @@ -1,8 +1,9 @@ package org.tron.core.db; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE; import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CREATION_TYPE; -import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import java.util.Objects; @@ -244,9 +245,8 @@ public void pay() throws BalanceInsufficientException { callerAccount = callContract.getOwnerAddress().toByteArray(); originAccount = contractCapsule.getOriginAddress(); - percent = Math - .max(Constant.ONE_HUNDRED - contractCapsule.getConsumeUserResourcePercent(), 0); - percent = Math.min(percent, Constant.ONE_HUNDRED); + percent = max(Constant.ONE_HUNDRED - contractCapsule.getConsumeUserResourcePercent(), 0); + percent = min(percent, Constant.ONE_HUNDRED); originEnergyLimit = contractCapsule.getOriginEnergyLimit(); break; default: diff --git a/chainbase/src/main/java/org/tron/core/service/MortgageService.java b/chainbase/src/main/java/org/tron/core/service/MortgageService.java index 805245d53f2..c618126c27b 100644 --- a/chainbase/src/main/java/org/tron/core/service/MortgageService.java +++ b/chainbase/src/main/java/org/tron/core/service/MortgageService.java @@ -1,5 +1,7 @@ package org.tron.core.service; +import static org.tron.common.math.StrictMathWrapper.min; + import com.google.protobuf.ByteString; import java.math.BigInteger; import java.util.Comparator; @@ -206,7 +208,7 @@ private long computeReward(long beginCycle, long endCycle, AccountCapsule accoun .map(vote -> new Pair<>(vote.getVoteAddress().toByteArray(), vote.getVoteCount())) .collect(Collectors.toList()); if (beginCycle < newAlgorithmCycle) { - long oldEndCycle = Math.min(endCycle, newAlgorithmCycle); + long oldEndCycle = min(endCycle, newAlgorithmCycle); reward = getOldReward(beginCycle, oldEndCycle, srAddresses); beginCycle = oldEndCycle; } diff --git a/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java b/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java index d38a5f0677e..4f69a6c3c66 100644 --- a/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java +++ b/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java @@ -43,13 +43,6 @@ private List getAssetIssuesPaginated(List return null; } -// return Streams.stream(iterator()) -// .map(Entry::getValue) -// .sorted(Comparator.comparing(a -> a.getName().toStringUtf8(), String::compareTo)) -// .skip(offset) -// .limit(Math.min(limit, ASSET_ISSUE_COUNT_LIMIT_MAX)) -// .collect(Collectors.toList()); - if (assetIssueList.size() <= offset) { return null; } 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 4af338f09bb..a523c24fd24 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -1,5 +1,6 @@ package org.tron.core.store; +import static org.tron.common.math.StrictMathWrapper.max; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; @@ -2240,7 +2241,7 @@ public void addTotalNetWeight(long amount) { long totalNetWeight = getTotalNetWeight(); totalNetWeight += amount; if (allowNewReward()) { - totalNetWeight = Math.max(0, totalNetWeight); + totalNetWeight = max(0, totalNetWeight); } saveTotalNetWeight(totalNetWeight); } @@ -2253,7 +2254,7 @@ public void addTotalEnergyWeight(long amount) { long totalEnergyWeight = getTotalEnergyWeight(); totalEnergyWeight += amount; if (allowNewReward()) { - totalEnergyWeight = Math.max(0, totalEnergyWeight); + totalEnergyWeight = max(0, totalEnergyWeight); } saveTotalEnergyWeight(totalEnergyWeight); } @@ -2266,7 +2267,7 @@ public void addTotalTronPowerWeight(long amount) { long totalWeight = getTotalTronPowerWeight(); totalWeight += amount; if (allowNewReward()) { - totalWeight = Math.max(0, totalWeight); + totalWeight = max(0, totalWeight); } saveTotalTronPowerWeight(totalWeight); } diff --git a/common/src/main/java/org/tron/common/math/StrictMathWrapper.java b/common/src/main/java/org/tron/common/math/StrictMathWrapper.java index 6285f6567c0..9e4d36f27a3 100644 --- a/common/src/main/java/org/tron/common/math/StrictMathWrapper.java +++ b/common/src/main/java/org/tron/common/math/StrictMathWrapper.java @@ -5,4 +5,151 @@ public class StrictMathWrapper { public static double pow(double a, double b) { return StrictMath.pow(a, b); } + + /** + * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call start *** + */ + + /** + * finally calls {@link java.lang.Math#addExact(long, long)} + */ + + public static long addExact(long x, long y) { + return StrictMath.addExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#addExact(int, int)} + */ + + public static int addExact(int x, int y) { + return StrictMath.addExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#subtractExact(long, long)} + */ + + public static long subtractExact(long x, long y) { + return StrictMath.subtractExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#floorMod(long, long)} + */ + public static long multiplyExact(long x, long y) { + return StrictMath.multiplyExact(x, y); + } + + public static long multiplyExact(long x, int y) { + return multiplyExact(x, (long) y); + } + + public static int multiplyExact(int x, int y) { + return StrictMath.multiplyExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#floorDiv(long, long)} + */ + public static long floorDiv(long x, long y) { + return StrictMath.floorDiv(x, y); + } + + public static long floorDiv(long x, int y) { + return floorDiv(x, (long) y); + } + + /** + * finally calls {@link java.lang.Math#min(int, int)} + */ + public static int min(int a, int b) { + return StrictMath.min(a, b); + } + + /** + * finally calls {@link java.lang.Math#min(long, long)} + */ + public static long min(long a, long b) { + return StrictMath.min(a, b); + } + + /** + * finally calls {@link java.lang.Math#max(int, int)} + */ + public static int max(int a, int b) { + return StrictMath.max(a, b); + } + + /** + * finally calls {@link java.lang.Math#max(long, long)} + */ + public static long max(long a, long b) { + return StrictMath.max(a, b); + } + + /** + * finally calls {@link java.lang.Math#round(float)} + */ + public static int round(float a) { + return StrictMath.round(a); + } + + /** + * finally calls {@link java.lang.Math#round(double)} + */ + public static long round(double a) { + return StrictMath.round(a); + } + + /** + * finally calls {@link java.lang.Math#signum(double)} + */ + public static double signum(double d) { + return StrictMath.signum(d); + } + + /** + * finally calls {@link java.lang.Math#signum(float)} + */ + public static long abs(long a) { + return StrictMath.abs(a); + } + + /** + * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call end *** + */ + + /** + * *** methods are same as {@link java.lang.Math} methods by mathematical algorithms*** + * / + + + /** + * mathematical integer: ceil(i) = floor(i) = i + * @return the smallest (closest to negative infinity) double value that is greater + * than or equal to the argument and is equal to a mathematical integer. + * Note: you should call {@link #ceilAsInt(double)} or {@link #ceilAsLong(double)} + * instead of this method. + */ + public static double ceil(double a) { + return StrictMath.ceil(a); + } + + public static long ceilAsLong(double a) { + return (long) ceil(a); + } + + public static int ceilAsInt(double a) { + return (int) ceil(a); + } + + + /** + * *** methods are no matters *** + */ + public static double random() { + return StrictMath.random(); + } + } diff --git a/common/src/main/java/org/tron/common/runtime/vm/DataWord.java b/common/src/main/java/org/tron/common/runtime/vm/DataWord.java index 0eb0487a534..0b5ea506674 100644 --- a/common/src/main/java/org/tron/common/runtime/vm/DataWord.java +++ b/common/src/main/java/org/tron/common/runtime/vm/DataWord.java @@ -29,6 +29,9 @@ import org.tron.common.utils.FastByteComparisons; import org.tron.core.db.ByteArrayWrapper; +import static org.tron.common.math.StrictMathWrapper.min; +import static org.tron.common.math.StrictMathWrapper.signum; + /** * DataWord is the 32-byte array representation of a 256-bit number Calculations can be done on this * word with other DataWords @@ -165,7 +168,7 @@ public byte[] getClonedData() { byte[] ret = ByteUtil.EMPTY_BYTE_ARRAY; if (data != null) { ret = new byte[WORD_SIZE]; - int dataSize = Math.min(data.length, WORD_SIZE); + int dataSize = min(data.length, WORD_SIZE); System.arraycopy(data, 0, ret, 0, dataSize); } return ret; @@ -484,7 +487,7 @@ public int compareTo(DataWord o) { data, 0, data.length, o.getData(), 0, o.getData().length); // Convert result into -1, 0 or 1 as is the convention - return (int) Math.signum(result); + return (int) signum(result); } public void signExtend(byte k) { diff --git a/common/src/main/java/org/tron/common/utils/ByteUtil.java b/common/src/main/java/org/tron/common/utils/ByteUtil.java index 54d637d3f01..480eb2b372d 100644 --- a/common/src/main/java/org/tron/common/utils/ByteUtil.java +++ b/common/src/main/java/org/tron/common/utils/ByteUtil.java @@ -32,6 +32,8 @@ import java.util.zip.Inflater; import org.tron.core.exception.EventBloomException; +import static org.tron.common.math.StrictMathWrapper.min; + public class ByteUtil { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; @@ -70,7 +72,7 @@ public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; - int length = Math.min(biBytes.length, numBytes); + int length = min(biBytes.length, numBytes); System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; } @@ -346,7 +348,7 @@ public static byte[] parseBytes(byte[] input, int offset, int len) { } byte[] bytes = new byte[len]; - System.arraycopy(input, offset, bytes, 0, Math.min(input.length - offset, len)); + System.arraycopy(input, offset, bytes, 0, min(input.length - offset, len)); return bytes; } diff --git a/framework/src/main/java/org/tron/common/logsfilter/ContractEventParser.java b/framework/src/main/java/org/tron/common/logsfilter/ContractEventParser.java index b2d8a0d8d3a..7ddabbd7ca4 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/ContractEventParser.java +++ b/framework/src/main/java/org/tron/common/logsfilter/ContractEventParser.java @@ -1,5 +1,7 @@ package org.tron.common.logsfilter; +import static org.tron.common.math.StrictMathWrapper.min; + import java.math.BigInteger; import java.util.regex.Pattern; import lombok.extern.slf4j.Slf4j; @@ -76,7 +78,7 @@ protected static byte[] subBytes(byte[] src, int start, int length) { throw new OutputLengthException("data start:" + start + ", length:" + length); } byte[] dst = new byte[length]; - System.arraycopy(src, start, dst, 0, Math.min(length, src.length - start)); + System.arraycopy(src, start, dst, 0, min(length, src.length - start)); return dst; } diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 0943723f2f4..22477e193c5 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -18,6 +18,9 @@ package org.tron.core; +import static org.tron.common.math.StrictMathWrapper.addExact; +import static org.tron.common.math.StrictMathWrapper.ceilAsLong; +import static org.tron.common.math.StrictMathWrapper.max; import static org.tron.common.utils.Commons.getAssetIssueStoreFinal; import static org.tron.common.utils.Commons.getExchangeStoreFinal; import static org.tron.common.utils.WalletUtil.isConstant; @@ -883,7 +886,7 @@ public long calcCanDelegatedBandWidthMaxSize( long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage); long maxSize = ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage; - return Math.max(0, maxSize); + return max(0, maxSize); } public long calcCanDelegatedEnergyMaxSize(ByteString ownerAddress) { @@ -903,7 +906,7 @@ public long calcCanDelegatedEnergyMaxSize(ByteString ownerAddress) { long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage); long maxSize = ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage; - return Math.max(0, maxSize); + return max(0, maxSize); } public DelegatedResourceAccountIndex getDelegatedResourceAccountIndex(ByteString address) { @@ -2975,7 +2978,7 @@ public Transaction estimateEnergy(TriggerSmartContract triggerSmartContract, if (transaction.getRet(0).getRet().equals(code.SUCESS)) { txRetBuilder.setResult(true); txRetBuilder.setCode(response_code.SUCCESS); - estimateBuilder.setEnergyRequired((long) Math.ceil((double) high / dps.getEnergyFee())); + estimateBuilder.setEnergyRequired(ceilAsLong((double) high / dps.getEnergyFee())); } return transaction; @@ -3529,8 +3532,8 @@ public ShieldedTRC20Parameters createShieldedContractParameters( long totalToAmount = 0; if (scaledToAmount > 0) { try { - totalToAmount = receiveSize == 0 ? scaledToAmount - : (Math.addExact(scaledToAmount, shieldedReceives.get(0).getNote().getValue())); + totalToAmount = receiveSize == 0 ? scaledToAmount : (addExact( + scaledToAmount, shieldedReceives.get(0).getNote().getValue())); } catch (ArithmeticException e) { throw new ZksnarkException("Unbalanced burn!"); } @@ -3661,8 +3664,8 @@ public ShieldedTRC20Parameters createShieldedContractParametersWithoutAsk( long totalToAmount = 0; if (scaledToAmount > 0) { try { - totalToAmount = receiveSize == 0 ? scaledToAmount - : Math.addExact(scaledToAmount, shieldedReceives.get(0).getNote().getValue()); + totalToAmount = receiveSize == 0 ? scaledToAmount : addExact( + scaledToAmount, shieldedReceives.get(0).getNote().getValue()); } catch (ArithmeticException e) { throw new ZksnarkException("Unbalanced burn!"); } diff --git a/framework/src/main/java/org/tron/core/capsule/utils/RLP.java b/framework/src/main/java/org/tron/core/capsule/utils/RLP.java index 60a84cfd3d3..3f5cd03312d 100644 --- a/framework/src/main/java/org/tron/core/capsule/utils/RLP.java +++ b/framework/src/main/java/org/tron/core/capsule/utils/RLP.java @@ -3,6 +3,7 @@ import static java.util.Arrays.copyOfRange; import static org.bouncycastle.util.Arrays.concatenate; import static org.bouncycastle.util.BigIntegers.asUnsignedByteArray; +import static org.tron.common.math.StrictMathWrapper.pow; import static org.tron.common.utils.ByteUtil.byteArrayToInt; import static org.tron.common.utils.ByteUtil.intToBytesNoLeadZeroes; import static org.tron.common.utils.ByteUtil.isNullOrZeroArray; @@ -49,7 +50,7 @@ public class RLP { /** * Allow for content up to size of 2^64 bytes * */ - private static final double MAX_ITEM_LENGTH = Math.pow(256, 8); + private static final double MAX_ITEM_LENGTH = pow(256, 8); /** * Reason for threshold according to Vitalik Buterin: - 56 bytes maximizes the benefit of both * options - if we went with 60 then we would have only had 4 slots for long strings so RLP would diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index 8853971a5f8..f685fafeef6 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -1,7 +1,8 @@ package org.tron.core.config.args; -import static java.lang.Math.max; import static java.lang.System.exit; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.Constant.ADD_PRE_FIX_BYTE_MAINNET; import static org.tron.core.Constant.DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE; import static org.tron.core.Constant.DYNAMIC_ENERGY_MAX_FACTOR_RANGE; @@ -1133,8 +1134,8 @@ public static void setParam(final String[] args, final String confFileName) { if (config.hasPath(Constant.ALLOW_DELEGATE_OPTIMIZATION)) { PARAMETER.allowDelegateOptimization = config.getLong(Constant.ALLOW_DELEGATE_OPTIMIZATION); - PARAMETER.allowDelegateOptimization = Math.min(PARAMETER.allowDelegateOptimization, 1); - PARAMETER.allowDelegateOptimization = Math.max(PARAMETER.allowDelegateOptimization, 0); + PARAMETER.allowDelegateOptimization = min(PARAMETER.allowDelegateOptimization, 1); + PARAMETER.allowDelegateOptimization = max(PARAMETER.allowDelegateOptimization, 0); } if (config.hasPath(Constant.COMMITTEE_UNFREEZE_DELAY_DAYS)) { @@ -1149,33 +1150,31 @@ public static void setParam(final String[] args, final String confFileName) { if (config.hasPath(Constant.ALLOW_DYNAMIC_ENERGY)) { PARAMETER.allowDynamicEnergy = config.getLong(Constant.ALLOW_DYNAMIC_ENERGY); - PARAMETER.allowDynamicEnergy = Math.min(PARAMETER.allowDynamicEnergy, 1); - PARAMETER.allowDynamicEnergy = Math.max(PARAMETER.allowDynamicEnergy, 0); + PARAMETER.allowDynamicEnergy = min(PARAMETER.allowDynamicEnergy, 1); + PARAMETER.allowDynamicEnergy = max(PARAMETER.allowDynamicEnergy, 0); } if (config.hasPath(Constant.DYNAMIC_ENERGY_THRESHOLD)) { PARAMETER.dynamicEnergyThreshold = config.getLong(Constant.DYNAMIC_ENERGY_THRESHOLD); PARAMETER.dynamicEnergyThreshold - = Math.min(PARAMETER.dynamicEnergyThreshold, 100_000_000_000_000_000L); - PARAMETER.dynamicEnergyThreshold = Math.max(PARAMETER.dynamicEnergyThreshold, 0); + = min(PARAMETER.dynamicEnergyThreshold, 100_000_000_000_000_000L); + PARAMETER.dynamicEnergyThreshold = max(PARAMETER.dynamicEnergyThreshold, 0); } if (config.hasPath(Constant.DYNAMIC_ENERGY_INCREASE_FACTOR)) { PARAMETER.dynamicEnergyIncreaseFactor = config.getLong(Constant.DYNAMIC_ENERGY_INCREASE_FACTOR); PARAMETER.dynamicEnergyIncreaseFactor = - Math.min(PARAMETER.dynamicEnergyIncreaseFactor, DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE); - PARAMETER.dynamicEnergyIncreaseFactor = - Math.max(PARAMETER.dynamicEnergyIncreaseFactor, 0); + min(PARAMETER.dynamicEnergyIncreaseFactor, DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE); + PARAMETER.dynamicEnergyIncreaseFactor = max(PARAMETER.dynamicEnergyIncreaseFactor, 0); } if (config.hasPath(Constant.DYNAMIC_ENERGY_MAX_FACTOR)) { PARAMETER.dynamicEnergyMaxFactor = config.getLong(Constant.DYNAMIC_ENERGY_MAX_FACTOR); PARAMETER.dynamicEnergyMaxFactor = - Math.min(PARAMETER.dynamicEnergyMaxFactor, DYNAMIC_ENERGY_MAX_FACTOR_RANGE); - PARAMETER.dynamicEnergyMaxFactor = - Math.max(PARAMETER.dynamicEnergyMaxFactor, 0); + min(PARAMETER.dynamicEnergyMaxFactor, DYNAMIC_ENERGY_MAX_FACTOR_RANGE); + PARAMETER.dynamicEnergyMaxFactor = max(PARAMETER.dynamicEnergyMaxFactor, 0); } PARAMETER.dynamicConfigEnable = config.hasPath(Constant.DYNAMIC_CONFIG_ENABLE) diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index 908e248bdee..0d3999aacda 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -1,5 +1,8 @@ package org.tron.core.db; +import static org.tron.common.math.StrictMathWrapper.floorDiv; +import static org.tron.common.math.StrictMathWrapper.max; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.common.utils.Commons.adjustBalance; import static org.tron.core.Constant.TRANSACTION_MAX_BYTE_SIZE; import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; @@ -1834,8 +1837,8 @@ private void payReward(BlockCapsule block) { mortgageService.payStandbyWitness(); if (chainBaseManager.getDynamicPropertiesStore().supportTransactionFeePool()) { - long transactionFeeReward = Math - .floorDiv(chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), + long transactionFeeReward = floorDiv( + chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), Constant.TRANSACTION_FEE_POOL_PERIOD); mortgageService.payTransactionFeeReward(witnessCapsule.getAddress().toByteArray(), transactionFeeReward); @@ -1850,8 +1853,8 @@ private void payReward(BlockCapsule block) { + chainBaseManager.getDynamicPropertiesStore().getWitnessPayPerBlock()); if (chainBaseManager.getDynamicPropertiesStore().supportTransactionFeePool()) { - long transactionFeeReward = Math - .floorDiv(chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), + long transactionFeeReward = floorDiv( + chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), Constant.TRANSACTION_FEE_POOL_PERIOD); account.setAllowance(account.getAllowance() + transactionFeeReward); chainBaseManager.getDynamicPropertiesStore().saveTransactionFeePool( @@ -2433,8 +2436,8 @@ private void initLiteNode() { } transactionCount += trx.getTransactionIds().size(); long blockNum = trx.getNum(); - maxBlock = Math.max(maxBlock, blockNum); - minBlock = Math.min(minBlock, blockNum); + maxBlock = max(maxBlock, blockNum); + minBlock = min(minBlock, blockNum); item.setBlockNum(blockNum); trx.getTransactionIds().forEach( tid -> chainBaseManager.getTransactionStore().put(Hex.decode(tid), item)); diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java index f575253c50c..e414a58bafc 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java @@ -1,5 +1,7 @@ package org.tron.core.net.messagehandler; +import static org.tron.common.math.StrictMathWrapper.min; + import java.util.LinkedList; import java.util.List; import lombok.extern.slf4j.Slf4j; @@ -117,7 +119,7 @@ private BlockId getUnForkId(List blockIds) throws P2pException { private LinkedList getBlockIds(Long unForkNum, BlockId headID) throws P2pException { long headNum = headID.getNum(); - long len = Math.min(headNum, unForkNum + NetConstants.SYNC_FETCH_BATCH_NUM); + long len = min(headNum, unForkNum + NetConstants.SYNC_FETCH_BATCH_NUM); LinkedList ids = new LinkedList<>(); for (long i = unForkNum; i <= len; i++) { diff --git a/framework/src/main/java/org/tron/core/net/service/effective/ResilienceService.java b/framework/src/main/java/org/tron/core/net/service/effective/ResilienceService.java index a63fd4bf0a9..6e619684866 100644 --- a/framework/src/main/java/org/tron/core/net/service/effective/ResilienceService.java +++ b/framework/src/main/java/org/tron/core/net/service/effective/ResilienceService.java @@ -1,5 +1,8 @@ package org.tron.core.net.service.effective; +import static org.tron.common.math.StrictMathWrapper.ceilAsInt; +import static org.tron.common.math.StrictMathWrapper.max; + import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -86,8 +89,8 @@ private void disconnectRandom() { long now = System.currentTimeMillis(); Map weights = new HashMap<>(); peers.forEach(peer -> { - int weight = (int) Math.ceil((double) (now - peer.getLastInteractiveTime()) / 500); - weights.put(peer, Math.max(weight, 1)); + int weight = ceilAsInt((double) (now - peer.getLastInteractiveTime()) / 500); + weights.put(peer, max(weight, 1)); }); WeightedRandom weightedRandom = new WeightedRandom(weights); PeerConnection one = (PeerConnection) weightedRandom.next(); diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java b/framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java index cf04a1769aa..df403d78dd5 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java @@ -1,5 +1,7 @@ package org.tron.core.services.jsonrpc.filters; +import static org.tron.common.math.StrictMathWrapper.min; + import com.google.protobuf.ByteString; import lombok.Getter; import org.apache.commons.lang3.StringUtils; @@ -55,7 +57,7 @@ public LogFilterWrapper(FilterRequest fr, long currentMaxBlockNum, Wallet wallet if (toBlockSrc == -1) { toBlockSrc = Long.MAX_VALUE; } - fromBlockSrc = Math.min(toBlockSrc, currentMaxBlockNum); + fromBlockSrc = min(toBlockSrc, currentMaxBlockNum); } else if (StringUtils.isNotEmpty(fr.getFromBlock()) && StringUtils.isEmpty(fr.getToBlock())) { diff --git a/framework/src/main/java/org/tron/program/DBConvert.java b/framework/src/main/java/org/tron/program/DBConvert.java index a13a2ffefb5..a4fb25fdbfa 100644 --- a/framework/src/main/java/org/tron/program/DBConvert.java +++ b/framework/src/main/java/org/tron/program/DBConvert.java @@ -1,6 +1,7 @@ package org.tron.program; import static org.fusesource.leveldbjni.JniDBFactory.factory; +import static org.tron.common.math.StrictMathWrapper.max; import java.io.File; import java.nio.file.Path; @@ -190,7 +191,7 @@ private Options newDefaultRocksDbOptions() { options.setTargetFileSizeBase(64 * 1024 * 1024); options.setTargetFileSizeMultiplier(1); options.setMaxBytesForLevelBase(512 * 1024 * 1024); - options.setMaxBackgroundCompactions(Math.max(1, Runtime.getRuntime().availableProcessors())); + options.setMaxBackgroundCompactions(max(1, Runtime.getRuntime().availableProcessors())); options.setLevel0FileNumCompactionTrigger(4); options.setLevelCompactionDynamicLevelBytes(true); if ("market_pair_price_to_order".equalsIgnoreCase(this.dbName)) { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java index 7debeb12772..55361fa67f1 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java @@ -15,6 +15,8 @@ package org.tron.common.runtime.vm; +import static org.tron.common.math.StrictMathWrapper.max; + import com.google.protobuf.Any; import com.google.protobuf.ByteString; import org.junit.Assert; @@ -248,7 +250,7 @@ public void testMaxContractResultSize() { continue; } Result result = Result.newBuilder().setContractRet(cr).build(); - maxSize = Math.max(maxSize, result.getSerializedSize()); + maxSize = max(maxSize, result.getSerializedSize()); } Assert.assertEquals(2, maxSize); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java index 9558c701109..c8dea48f26c 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java @@ -1,5 +1,6 @@ package org.tron.common.runtime.vm; +import static org.tron.common.math.StrictMathWrapper.min; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; @@ -856,7 +857,7 @@ private TVMTestResult unDelegateResource( transferUsage = (long) (oldReceiver.getEnergyUsage() * ((double) (amount) / oldReceiver.getAllFrozenBalanceForEnergy())); } - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); + transferUsage = min(unDelegateMaxUsage, transferUsage); } DelegatedResourceStore delegatedResourceStore = manager.getDelegatedResourceStore(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java b/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java index b6e9cfe109c..5b6785af014 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java @@ -18,9 +18,9 @@ package org.tron.common.runtime.vm; -import static java.lang.Math.ceil; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; +import static org.tron.common.math.StrictMathWrapper.ceilAsInt; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; @@ -43,7 +43,7 @@ private static void checkMemoryExtend(int dataSize) { } private static int calcSize(int dataSize, int chunkSize) { - return (int) ceil((double) dataSize / chunkSize) * chunkSize; + return ceilAsInt((double) dataSize / chunkSize) * chunkSize; } @Test diff --git a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java index 833ed6b0ac3..64b4e112cdc 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java @@ -1,6 +1,8 @@ package org.tron.common.runtime.vm; import static org.junit.Assert.assertNotNull; +import static org.tron.common.math.StrictMathWrapper.random; +import static org.tron.common.math.StrictMathWrapper.round; import com.google.protobuf.ByteString; import java.math.BigInteger; @@ -4504,7 +4506,7 @@ private byte[] longTo32Bytes(long value) { } private long randomLong() { - return Math.round(Math.random() * Long.MAX_VALUE / 2); + return round(random() * Long.MAX_VALUE / 2); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java index 1d85e9a7eab..69bb8f239ca 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java @@ -1,5 +1,6 @@ package org.tron.common.runtime.vm; +import static org.tron.common.math.StrictMathWrapper.max; import static org.tron.protos.Protocol.Transaction.Result.contractResult; import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT; import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; @@ -863,7 +864,7 @@ private void checkRewardAndWithdraw(byte[] contract, boolean isZero) throws Exce long rewardBySystem = mortgageService.queryReward(contract); long beginCycle = manager.getDelegationStore().getBeginCycle(contract); long currentCycle = manager.getDynamicPropertiesStore().getCurrentCycleNumber(); - long passedCycle = Math.max(0, currentCycle - beginCycle); + long passedCycle = max(0, currentCycle - beginCycle); Assert.assertTrue(isZero ? rewardBySystem == 0 : rewardBySystem > 0); triggerContract(contract, SUCCESS, getConsumer(">=", rewardBySystem) diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java index 976490b8c80..1c9aa8ea0cd 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java @@ -1,5 +1,7 @@ package org.tron.common.utils.client.utils; +import static org.tron.common.math.StrictMathWrapper.abs; + import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; @@ -340,7 +342,7 @@ static class CoderNumber extends Coder { @Override byte[] encode(String value) { long n = Long.valueOf(value); - DataWord word = new DataWord(Math.abs(n)); + DataWord word = new DataWord(abs(n)); if (n < 0) { word.negate(); } diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java index 6c36f4d636a..e2ea88a1a86 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java @@ -18,6 +18,8 @@ * along with the ethereumJ library. If not, see . */ +import static org.tron.common.math.StrictMathWrapper.signum; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigInteger; @@ -466,7 +468,7 @@ public int compareTo(DataWord o) { data, 0, data.length, o.getData(), 0, o.getData().length); // Convert result into -1, 0 or 1 as is the convention - return (int) Math.signum(result); + return (int) signum(result); } /** diff --git a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java index 3346a1aead5..77ab2008c26 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java @@ -3,6 +3,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.tron.common.math.StrictMathWrapper.max; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; @@ -114,7 +115,7 @@ public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsul TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), ContractType.DelegateResourceContract); long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); - long addSize = Math.max(size1 - size2, 0L); + long addSize = max(size1 - size2, 0L); return DELEGATE_COST_BASE_SIZE + addSize; } @@ -135,7 +136,7 @@ public static long estimateConsumeBandWidthSizeOld( TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), ContractType.DelegateResourceContract); long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); - long addSize = Math.max(size1 - size2, 0L); + long addSize = max(size1 - size2, 0L); return DELEGATE_COST_BASE_SIZE + addSize; } @@ -373,7 +374,7 @@ public void estimateConsumeBandWidthSizePositive() { DelegateResourceContract.newBuilder() .setBalance(TRX_PRECISION); - long expected = DELEGATE_COST_BASE_SIZE + Math.max( + long expected = DELEGATE_COST_BASE_SIZE + max( builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); @@ -391,7 +392,7 @@ public void estimateConsumeBandWidthSizeBoundary() { DelegateResourceContract.newBuilder() .setBalance(TRX_PRECISION); - long expected = DELEGATE_COST_BASE_SIZE + Math.max( + long expected = DELEGATE_COST_BASE_SIZE + max( builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); @@ -409,7 +410,7 @@ public void estimateConsumeBandWidthSizeEdge() { DelegateResourceContract.newBuilder() .setBalance(TRX_PRECISION); - long expected = DELEGATE_COST_BASE_SIZE + Math.max( + long expected = DELEGATE_COST_BASE_SIZE + max( builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); @@ -427,7 +428,7 @@ public void estimateConsumeBandWidthSizeCorner() { DelegateResourceContract.newBuilder() .setBalance(TRX_PRECISION); - long expected = DELEGATE_COST_BASE_SIZE + Math.max( + long expected = DELEGATE_COST_BASE_SIZE + max( builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); diff --git a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java index 910b1adba67..47af507c484 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java @@ -1,5 +1,7 @@ package org.tron.core.capsule.utils; +import static org.tron.common.math.StrictMathWrapper.pow; + import com.google.protobuf.ByteString; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -86,7 +88,7 @@ private static int getRank(int num) { num = num >> 1; rank++; } - if (temp == Math.pow(2, rank - 1)) { + if (temp == pow(2, rank - 1)) { rank -= 1; } return rank; diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index 1f453cb9b41..2e98b8f4351 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -1,5 +1,8 @@ package org.tron.core.db; +import static org.tron.common.math.StrictMathWrapper.random; +import static org.tron.common.math.StrictMathWrapper.round; + import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; @@ -43,7 +46,7 @@ public void cleanDb() { } private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random() * (maxInt - minInt) + minInt); } @Test diff --git a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java index ea0c0354bb0..e5fb70bf0e1 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -1,5 +1,8 @@ package org.tron.core.jsonrpc; +import static org.tron.common.math.StrictMathWrapper.random; +import static org.tron.common.math.StrictMathWrapper.round; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -17,7 +20,7 @@ public class ConcurrentHashMapTest { private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random() * (maxInt - minInt) + minInt); } /** diff --git a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java index 67353eb24b1..6ce1688d836 100644 --- a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java @@ -4,6 +4,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; +import static org.tron.common.math.StrictMathWrapper.random; +import static org.tron.common.math.StrictMathWrapper.round; import static org.tron.common.zksnark.JLibrustzcash.librustzcashCheckDiversifier; import static org.tron.common.zksnark.JLibrustzcash.librustzcashComputeCm; import static org.tron.common.zksnark.JLibrustzcash.librustzcashIvkToPkd; @@ -87,7 +89,7 @@ public static void init() { } private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random() * (maxInt - minInt) + minInt); } public static void test(byte[] K, byte[] ovk, byte[] cv, byte[] cm, byte[] epk) diff --git a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java index 60f6c8c0826..5c717b82d97 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java @@ -1,5 +1,8 @@ package org.tron.core.zksnark; +import static org.tron.common.math.StrictMathWrapper.random; +import static org.tron.common.math.StrictMathWrapper.round; + import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -30,7 +33,7 @@ public static void removeDb() { } private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random() * (maxInt - minInt) + minInt); } @Test diff --git a/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java b/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java index 3422c36ca9d..2922d110b7c 100644 --- a/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java +++ b/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java @@ -59,7 +59,7 @@ public static int compareUnsigned(byte[] a, byte[] b) { if (b == null) { return 1; } - int minLen = Math.min(a.length, b.length); + int minLen = StrictMath.min(a.length, b.length); for (int i = 0; i < minLen; ++i) { int aVal = a[i] & 0xFF; int bVal = b[i] & 0xFF; diff --git a/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java b/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java index 19547e2b5a5..f8559d5dba8 100644 --- a/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java +++ b/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java @@ -95,7 +95,8 @@ private static Options newDefaultRocksDbOptions(boolean forBulkLoad) { options.setTargetFileSizeBase(64 * 1024 * 1024); options.setTargetFileSizeMultiplier(1); options.setMaxBytesForLevelBase(512 * 1024 * 1024); - options.setMaxBackgroundCompactions(Math.max(1, Runtime.getRuntime().availableProcessors())); + options.setMaxBackgroundCompactions(StrictMath.max( + 1, Runtime.getRuntime().availableProcessors())); options.setLevel0FileNumCompactionTrigger(4); options.setLevelCompactionDynamicLevelBytes(true); final BlockBasedTableConfig tableCfg; diff --git a/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java b/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java index a36fc8ad57c..dbd578a59a3 100644 --- a/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java +++ b/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java @@ -130,8 +130,8 @@ public static int comparePriceKey(byte[] o1, byte[] o2) { public static int comparePrice(long price1SellQuantity, long price1BuyQuantity, long price2SellQuantity, long price2BuyQuantity) { try { - return Long.compare(Math.multiplyExact(price1BuyQuantity, price2SellQuantity), - Math.multiplyExact(price2BuyQuantity, price1SellQuantity)); + return Long.compare(StrictMath.multiplyExact(price1BuyQuantity, price2SellQuantity), + StrictMath.multiplyExact(price2BuyQuantity, price1SellQuantity)); } catch (ArithmeticException ex) { // do nothing here, because we will use BigInteger to compute again