Skip to content

Commit 55cd17f

Browse files
Merge pull request #6182 from halibobo1205/480/Math_full_to_strictMath
feat(math): migrate all operations from java.lang.Math to java.lang.strictMath
2 parents 3886068 + 61eb746 commit 55cd17f

File tree

86 files changed

+1036
-450
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+1036
-450
lines changed

.github/workflows/math-check.yml

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
name: Check Math Usage
2+
3+
on:
4+
push:
5+
branches: [ 'master', 'release_**' ]
6+
pull_request:
7+
branches: [ 'develop', 'release_**' ]
8+
workflow_dispatch:
9+
10+
jobs:
11+
check-math:
12+
runs-on: ubuntu-latest
13+
14+
steps:
15+
- uses: actions/checkout@v4
16+
17+
- name: Check for java.lang.Math usage
18+
id: check-math
19+
shell: bash
20+
run: |
21+
echo "Checking for java.lang.Math usage..."
22+
23+
touch math_usage.txt
24+
25+
while IFS= read -r file; do
26+
filename=$(basename "$file")
27+
if [[ "$filename" == "StrictMathWrapper.java" || "$filename" == "MathWrapper.java" ]]; then
28+
continue
29+
fi
30+
31+
perl -0777 -ne '
32+
s/"([^"\\]|\\.)*"//g;
33+
s/'\''([^'\''\\]|\\.)*'\''//g;
34+
s!/\*([^*]|\*[^/])*\*/!!g;
35+
s!//[^\n]*!!g;
36+
$hasMath = 0;
37+
$hasMath = 1 if /^[\s]*import[\s]+java\.lang\.Math\b/m;
38+
$hasMath = 1 if /\bjava\s*\.\s*lang\s*\.\s*Math\s*\./;
39+
$hasMath = 1 if /(?<![\w\.])(?<!Strict)Math\s*\./;
40+
print "$ARGV\n" if $hasMath;
41+
' "$file" >> math_usage.txt
42+
done < <(find . -type f -name "*.java")
43+
44+
sort -u math_usage.txt -o math_usage.txt
45+
46+
if [ -s math_usage.txt ]; then
47+
echo "❌ Error: Forbidden Math usage found in the following files:"
48+
cat math_usage.txt
49+
echo "math_found=true" >> $GITHUB_OUTPUT
50+
echo "Please use org.tron.common.math.StrictMathWrapper instead of direct Math usage."
51+
else
52+
echo "✅ No forbidden Math usage found"
53+
echo "math_found=false" >> $GITHUB_OUTPUT
54+
fi
55+
56+
- name: Upload findings
57+
if: steps.check-math.outputs.math_found == 'true'
58+
uses: actions/upload-artifact@v4
59+
with:
60+
name: math-usage-report
61+
path: math_usage.txt
62+
63+
- name: Create comment
64+
if: github.event_name == 'pull_request' && steps.check-math.outputs.math_found == 'true'
65+
uses: actions/github-script@v6
66+
with:
67+
script: |
68+
const fs = require('fs');
69+
const findings = fs.readFileSync('math_usage.txt', 'utf8');
70+
const body = `### ❌ Math Usage Detection Results
71+
72+
Found forbidden usage of \`java.lang.Math\` in the following files:
73+
74+
\`\`\`
75+
${findings}
76+
\`\`\`
77+
78+
**Please review if this usage is intended.**
79+
> [!CAUTION]
80+
> Note: You should use \`org.tron.common.math.StrictMathWrapper\`.
81+
> If you need to use \`java.lang.Math\`, please provide a justification.
82+
`;
83+
84+
await github.rest.issues.createComment({
85+
owner: context.repo.owner,
86+
repo: context.repo.repo,
87+
issue_number: context.issue.number,
88+
body: body
89+
});
90+
91+
- name: Fail if Math usage found
92+
if: steps.check-math.outputs.math_found == 'true'
93+
run: exit 1

actuator/src/main/java/org/tron/core/actuator/AbstractActuator.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@
22

33
import com.google.protobuf.Any;
44
import com.google.protobuf.GeneratedMessageV3;
5+
import org.tron.common.math.Maths;
6+
import org.tron.common.utils.Commons;
57
import org.tron.common.utils.ForkController;
68
import org.tron.core.ChainBaseManager;
9+
import org.tron.core.capsule.AccountCapsule;
710
import org.tron.core.capsule.TransactionCapsule;
11+
import org.tron.core.exception.BalanceInsufficientException;
12+
import org.tron.core.store.AccountStore;
813
import org.tron.protos.Protocol.Transaction.Contract;
914
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
1015

@@ -63,4 +68,61 @@ public AbstractActuator setForkUtils(ForkController forkController) {
6368
return this;
6469
}
6570

71+
public long addExact(long x, long y) {
72+
return Maths.addExact(x, y, chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
73+
}
74+
75+
public long addExact(int x, int y) {
76+
return Maths.addExact(x, y, chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
77+
}
78+
79+
public long floorDiv(long x, long y) {
80+
return Maths.floorDiv(x, y, chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
81+
}
82+
83+
public long floorDiv(long x, int y) {
84+
return this.floorDiv(x, (long) y);
85+
}
86+
87+
public long multiplyExact(long x, long y) {
88+
return Maths.multiplyExact(x, y,
89+
chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
90+
}
91+
92+
public long multiplyExact(long x, int y) {
93+
return this.multiplyExact(x, (long) y);
94+
}
95+
96+
public int multiplyExact(int x, int y) {
97+
return Maths.multiplyExact(x, y,
98+
chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
99+
}
100+
101+
public long subtractExact(long x, long y) {
102+
return Maths.subtractExact(x, y,
103+
chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
104+
}
105+
106+
public int min(int a, int b) {
107+
return Maths.min(a, b, chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
108+
}
109+
110+
public long min(long a, long b) {
111+
return Maths.min(a, b, chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
112+
}
113+
114+
public void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount)
115+
throws BalanceInsufficientException {
116+
AccountCapsule account = accountStore.getUnchecked(accountAddress);
117+
this.adjustBalance(accountStore, account, amount);
118+
}
119+
120+
/**
121+
* judge balance.
122+
*/
123+
public void adjustBalance(AccountStore accountStore, AccountCapsule account, long amount)
124+
throws BalanceInsufficientException {
125+
Commons.adjustBalance(accountStore, account, amount,
126+
chainBaseManager.getDynamicPropertiesStore().allowStrictMath2());
127+
}
66128
}

actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import java.util.Objects;
99
import lombok.extern.slf4j.Slf4j;
1010
import org.apache.commons.lang3.StringUtils;
11-
import org.tron.common.utils.Commons;
1211
import org.tron.common.utils.DecodeUtil;
1312
import org.tron.core.capsule.AccountCapsule;
1413
import org.tron.core.capsule.TransactionResultCapsule;
@@ -52,11 +51,11 @@ public boolean execute(Object object) throws ContractExeException {
5251
accountPermissionUpdateContract.getActivesList());
5352
accountStore.put(ownerAddress, account);
5453

55-
Commons.adjustBalance(accountStore, ownerAddress, -fee);
54+
adjustBalance(accountStore, ownerAddress, -fee);
5655
if (chainBaseManager.getDynamicPropertiesStore().supportBlackHoleOptimization()) {
5756
chainBaseManager.getDynamicPropertiesStore().burnTrx(fee);
5857
} else {
59-
Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);
58+
adjustBalance(accountStore, accountStore.getBlackhole(), fee);
6059
}
6160

6261
result.setStatus(fee, code.SUCESS);
@@ -111,7 +110,7 @@ private boolean checkPermission(Permission permission) throws ContractValidateEx
111110
throw new ContractValidateException("key's weight should be greater than 0");
112111
}
113112
try {
114-
weightSum = Math.addExact(weightSum, key.getWeight());
113+
weightSum = addExact(weightSum, key.getWeight());
115114
} catch (ArithmeticException e) {
116115
throw new ContractValidateException(e.getMessage());
117116
}

actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
import java.util.List;
2525
import java.util.Objects;
2626
import lombok.extern.slf4j.Slf4j;
27-
import org.tron.common.utils.Commons;
2827
import org.tron.common.utils.DecodeUtil;
2928
import org.tron.core.capsule.AccountCapsule;
3029
import org.tron.core.capsule.AssetIssueCapsule;
@@ -84,11 +83,11 @@ public boolean execute(Object result) throws ContractExeException {
8483
.put(assetIssueCapsuleV2.createDbV2Key(), assetIssueCapsuleV2);
8584
}
8685

87-
Commons.adjustBalance(accountStore, ownerAddress, -fee);
86+
adjustBalance(accountStore, ownerAddress, -fee);
8887
if (dynamicStore.supportBlackHoleOptimization()) {
8988
dynamicStore.burnTrx(fee);
9089
} else {
91-
Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);//send to blackhole
90+
adjustBalance(accountStore, accountStore.getBlackhole(), fee);//send to blackhole
9291
}
9392
AccountCapsule accountCapsule = accountStore.get(ownerAddress);
9493
List<FrozenSupply> frozenSupplyList = assetIssueContract.getFrozenSupplyList();

actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import com.google.protobuf.InvalidProtocolBufferException;
77
import java.util.Objects;
88
import lombok.extern.slf4j.Slf4j;
9-
import org.tron.common.utils.Commons;
109
import org.tron.common.utils.DecodeUtil;
1110
import org.tron.common.utils.StringUtil;
1211
import org.tron.core.capsule.AccountCapsule;
@@ -48,13 +47,12 @@ public boolean execute(Object result)
4847
accountStore
4948
.put(accountCreateContract.getAccountAddress().toByteArray(), accountCapsule);
5049

51-
Commons
52-
.adjustBalance(accountStore, accountCreateContract.getOwnerAddress().toByteArray(), -fee);
50+
adjustBalance(accountStore, accountCreateContract.getOwnerAddress().toByteArray(), -fee);
5351
// Add to blackhole address
5452
if (dynamicStore.supportBlackHoleOptimization()) {
5553
dynamicStore.burnTrx(fee);
5654
} else {
57-
Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);
55+
adjustBalance(accountStore, accountStore.getBlackhole(), fee);
5856
}
5957
ret.setStatus(fee, code.SUCESS);
6058
} catch (BalanceInsufficientException | InvalidProtocolBufferException e) {

actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,8 @@ public boolean validate() throws ContractValidateException {
162162
}
163163
long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double)
164164
(dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit()));
165-
long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage);
165+
long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage,
166+
dynamicStore.allowStrictMath2());
166167
if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) {
167168
throw new ContractValidateException(
168169
"delegateBalance must be less than or equal to available FreezeBandwidthV2 balance");
@@ -175,7 +176,8 @@ public boolean validate() throws ContractValidateException {
175176

176177
long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double)
177178
(dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit()));
178-
long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage);
179+
long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage,
180+
dynamicStore.allowStrictMath2());
179181
if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) {
180182
throw new ContractValidateException(
181183
"delegateBalance must be less than or equal to available FreezeEnergyV2 balance");

actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import java.util.Arrays;
1010
import java.util.Objects;
1111
import lombok.extern.slf4j.Slf4j;
12-
import org.tron.common.utils.Commons;
1312
import org.tron.common.utils.DecodeUtil;
1413
import org.tron.common.utils.StringUtil;
1514
import org.tron.core.capsule.AccountCapsule;
@@ -121,7 +120,7 @@ public boolean execute(Object object) throws ContractExeException {
121120
if (dynamicStore.supportBlackHoleOptimization()) {
122121
dynamicStore.burnTrx(fee);
123122
} else {
124-
Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);
123+
adjustBalance(accountStore, accountStore.getBlackhole(), fee);
125124
}
126125
ret.setExchangeId(id);
127126
ret.setStatus(fee, code.SUCESS);

actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,14 @@ public boolean execute(Object object) throws ContractExeException {
7171

7272
if (Arrays.equals(tokenID, firstTokenID)) {
7373
anotherTokenID = secondTokenID;
74-
anotherTokenQuant = Math
75-
.floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance);
74+
anotherTokenQuant = floorDiv(multiplyExact(
75+
secondTokenBalance, tokenQuant), firstTokenBalance);
7676
exchangeCapsule.setBalance(firstTokenBalance + tokenQuant,
7777
secondTokenBalance + anotherTokenQuant);
7878
} else {
7979
anotherTokenID = firstTokenID;
80-
anotherTokenQuant = Math
81-
.floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance);
80+
anotherTokenQuant = floorDiv(multiplyExact(
81+
firstTokenBalance, tokenQuant), secondTokenBalance);
8282
exchangeCapsule.setBalance(firstTokenBalance + anotherTokenQuant,
8383
secondTokenBalance + tokenQuant);
8484
}

actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,12 @@ public boolean execute(Object object) throws ContractExeException {
7676
BigInteger bigTokenQuant = new BigInteger(String.valueOf(tokenQuant));
7777
if (Arrays.equals(tokenID, firstTokenID)) {
7878
anotherTokenID = secondTokenID;
79-
// anotherTokenQuant = Math
80-
// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance);
8179
anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant)
8280
.divide(bigFirstTokenBalance).longValueExact();
8381
exchangeCapsule.setBalance(firstTokenBalance - tokenQuant,
8482
secondTokenBalance - anotherTokenQuant);
8583
} else {
8684
anotherTokenID = firstTokenID;
87-
// anotherTokenQuant = Math
88-
// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance);
8985
anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant)
9086
.divide(bigSecondTokenBalance).longValueExact();
9187
exchangeCapsule.setBalance(firstTokenBalance - anotherTokenQuant,
@@ -210,8 +206,6 @@ public boolean validate() throws ContractValidateException {
210206
BigDecimal bigSecondTokenBalance = new BigDecimal(String.valueOf(secondTokenBalance));
211207
BigDecimal bigTokenQuant = new BigDecimal(String.valueOf(tokenQuant));
212208
if (Arrays.equals(tokenID, firstTokenID)) {
213-
// anotherTokenQuant = Math
214-
// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance);
215209
anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant)
216210
.divideToIntegralValue(bigFirstTokenBalance).longValueExact();
217211
if (firstTokenBalance < tokenQuant || secondTokenBalance < anotherTokenQuant) {
@@ -230,8 +224,6 @@ public boolean validate() throws ContractValidateException {
230224
}
231225

232226
} else {
233-
// anotherTokenQuant = Math
234-
// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance);
235227
anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant)
236228
.divideToIntegralValue(bigSecondTokenBalance).longValueExact();
237229
if (secondTokenBalance < tokenQuant || firstTokenBalance < anotherTokenQuant) {

actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import com.google.protobuf.InvalidProtocolBufferException;
2424
import java.util.Objects;
2525
import lombok.extern.slf4j.Slf4j;
26-
import org.tron.common.utils.Commons;
2726
import org.tron.common.utils.DecodeUtil;
2827
import org.tron.core.capsule.AccountCapsule;
2928
import org.tron.core.capsule.MarketOrderCapsule;
@@ -100,7 +99,7 @@ public boolean execute(Object object) throws ContractExeException {
10099
if (dynamicStore.supportBlackHoleOptimization()) {
101100
dynamicStore.burnTrx(fee);
102101
} else {
103-
Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);
102+
adjustBalance(accountStore, accountStore.getBlackhole(), fee);
104103
}
105104
// 1. return balance and token
106105
MarketUtils

0 commit comments

Comments
 (0)