Skip to content

Commit a283378

Browse files
committed
Merge branch 'add_energy_limit' of https://github.com/tronprotocol/java-tron into add_energy_limit
2 parents 183c5b6 + 1e5ac3e commit a283378

5 files changed

Lines changed: 88 additions & 14 deletions

File tree

‎src/main/java/org/tron/common/entity/NodeInfo.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ public ConfigNodeInfo setAllowCreationOfContracts(long allowCreationOfContracts)
473473
this.allowCreationOfContracts = allowCreationOfContracts;
474474
return this;
475475
}
476+
476477
}
477478

478479
public long getBeginSyncNum() {

‎src/main/java/org/tron/common/runtime/RuntimeImpl.java‎

Lines changed: 77 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272

7373
@Slf4j(topic = "Runtime")
7474
public class RuntimeImpl implements Runtime {
75+
7576
private VMConfig config = VMConfig.getInstance();
7677

7778
private Transaction trx;
@@ -178,7 +179,8 @@ public BigInteger getBlockCPULeftInUs() {
178179
// insure blockCap is not null
179180
BigInteger curBlockHaveElapsedCPUInUs =
180181
BigInteger.valueOf(
181-
Constant.ONE_THOUSAND * (DateTime.now().getMillis() - blockCap.getInstance().getBlockHeader()
182+
Constant.ONE_THOUSAND * (DateTime.now().getMillis() - blockCap.getInstance()
183+
.getBlockHeader()
182184
.getRawData()
183185
.getTimestamp())); // us
184186
BigInteger curBlockCPULimitInUs = BigInteger.valueOf((long)
@@ -207,10 +209,28 @@ public void execute()
207209
}
208210
}
209211

212+
private long getEnergyLimit2(AccountCapsule account, long feeLimit, long callValue) {
213+
214+
long sunPerEnergy = Constant.SUN_PER_ENERGY;
215+
if (deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee() != 0) {
216+
sunPerEnergy = deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee();
217+
}
218+
219+
long leftFrozenEnergy = energyProcessor.getAccountLeftEnergyFromFreeze(account);
220+
callValue = max(callValue, 0);
221+
long energyFromBalance = Math.floorDiv(max(account.getBalance() - callValue, 0), sunPerEnergy);
222+
long availableEnergy = Math.addExact(leftFrozenEnergy, energyFromBalance);
223+
224+
long energyFromFeeLimit = feeLimit / sunPerEnergy;
225+
226+
return min(availableEnergy, energyFromFeeLimit);
227+
228+
}
229+
210230
private long getEnergyLimit(AccountCapsule account, long feeLimit, long callValue) {
211231

212232
long sunPerEnergy = Constant.SUN_PER_ENERGY;
213-
if (deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee() != 0){
233+
if (deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee() != 0) {
214234
sunPerEnergy = deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee();
215235
}
216236
// can change the calc way
@@ -270,6 +290,42 @@ private long getEnergyLimit(AccountCapsule creator, AccountCapsule caller,
270290
}
271291
}
272292

293+
private long getEnergyLimit2(AccountCapsule creator, AccountCapsule caller,
294+
TriggerSmartContract contract, long feeLimit, long callValue) {
295+
296+
long callerEnergyLimit = getEnergyLimit2(caller, feeLimit, callValue);
297+
if (Arrays.equals(creator.getAddress().toByteArray(), caller.getAddress().toByteArray())) {
298+
return callerEnergyLimit;
299+
}
300+
301+
// creatorEnergyFromFreeze
302+
long creatorEnergyLimit;
303+
304+
SmartContract smartContract = this.deposit
305+
.getContract(contract.getContractAddress().toByteArray()).getInstance();
306+
long consumeUserResourcePercent = smartContract.getConsumeUserResourcePercent();
307+
consumeUserResourcePercent = max(0, min(consumeUserResourcePercent, Constant.ONE_HUNDRED));
308+
309+
long creatorMaxEnergy = smartContract.getEnergyLimit();
310+
if (creatorMaxEnergy == Constant.PB_DEFAULT_ENERGY_LIMIT) {
311+
creatorMaxEnergy = Constant.CREATOR_DEFAULT_ENERGY_LIMIT;
312+
}
313+
314+
if (consumeUserResourcePercent == 0) {
315+
creatorEnergyLimit = min(energyProcessor.getAccountLeftEnergyFromFreeze(creator),
316+
creatorMaxEnergy);
317+
} else {
318+
creatorEnergyLimit = min(
319+
BigInteger.valueOf(callerEnergyLimit)
320+
.multiply(BigInteger.valueOf(Constant.ONE_HUNDRED - consumeUserResourcePercent))
321+
.divide(BigInteger.valueOf(consumeUserResourcePercent)).longValueExact(),
322+
min(energyProcessor.getAccountLeftEnergyFromFreeze(creator), creatorMaxEnergy));
323+
}
324+
325+
return Math.addExact(callerEnergyLimit, creatorEnergyLimit);
326+
327+
}
328+
273329
private double getThisTxCPULimitInUsRatio() {
274330

275331
double thisTxCPULimitInUsRatio;
@@ -280,7 +336,7 @@ private double getThisTxCPULimitInUsRatio() {
280336
this.blockCap.getInstance().getBlockHeader().getWitnessSignature().isEmpty()) {
281337
thisTxCPULimitInUsRatio = 1.0;
282338
} else {
283-
// self witness 3, other witness 3, fullnode 2
339+
// self witness 3, other witness 2, fullnode 2
284340
if (trx.getRet(0).getContractRet() == contractResult.OUT_OF_TIME) {
285341
thisTxCPULimitInUsRatio = Args.getInstance().getMinTimeRatio();
286342
} else {
@@ -346,7 +402,13 @@ private void create()
346402

347403
AccountCapsule creator = this.deposit
348404
.getAccount(newSmartContract.getOriginAddress().toByteArray());
349-
long energyLimit = getEnergyLimit(creator, feeLimit, callValue);
405+
406+
long energyLimit;
407+
if (false) { // TODO according to version
408+
energyLimit = getEnergyLimit2(creator, feeLimit, callValue);
409+
} else {
410+
energyLimit = getEnergyLimit(creator, feeLimit, callValue);
411+
}
350412
byte[] ops = newSmartContract.getBytecode().toByteArray();
351413
rootInternalTransaction = new InternalTransaction(trx, trxType);
352414

@@ -359,7 +421,8 @@ private void create()
359421
.createProgramInvoke(TRX_CONTRACT_CREATION_TYPE, executorType, trx,
360422
blockCap.getInstance(), deposit, vmStartInUs, vmShouldEndInUs, energyLimit);
361423
this.vm = new VM(config);
362-
this.program = new Program(ops, programInvoke, rootInternalTransaction, config, this.blockCap);
424+
this.program = new Program(ops, programInvoke, rootInternalTransaction, config,
425+
this.blockCap);
363426
this.program.setRootTransactionId(new TransactionCapsule(trx).getTransactionId().getBytes());
364427
this.program.setRootCallConstant(isCallConstant());
365428
} catch (Exception e) {
@@ -401,7 +464,7 @@ private void call()
401464
return;
402465
}
403466

404-
if(contract.getContractAddress() == null) {
467+
if (contract.getContractAddress() == null) {
405468
throw new ContractValidateException("Cannot get contract address from TriggerContract");
406469
}
407470

@@ -426,12 +489,17 @@ private void call()
426489
long energyLimit;
427490
if (isCallConstant(contractAddress)) {
428491
isStaticCall = true;
429-
energyLimit = Constant.MAX_ENERGY_IN_TX;
492+
energyLimit = Constant.ENERGY_LIMIT_IN_CONSTANT_TX;
430493
} else {
431494
AccountCapsule creator = this.deposit.getAccount(
432495
deployedContract.getInstance()
433496
.getOriginAddress().toByteArray());
434-
energyLimit = getEnergyLimit(creator, caller, contract, feeLimit, callValue);
497+
498+
if (false) { // TODO according to version
499+
energyLimit = getEnergyLimit2(creator, caller, contract, feeLimit, callValue);
500+
} else {
501+
energyLimit = getEnergyLimit(creator, caller, contract, feeLimit, callValue);
502+
}
435503
}
436504
long maxCpuTimeOfOneTx = deposit.getDbManager().getDynamicPropertiesStore()
437505
.getMaxCpuTimeOfOneTx() * Constant.ONE_THOUSAND;
@@ -596,6 +664,7 @@ private boolean isCallConstant(byte[] address) throws ContractValidateException
596664
}
597665
return false;
598666
}
667+
599668
public void finalization() {
600669
if (StringUtils.isEmpty(runtimeError)) {
601670
for (DataWord contract : result.getDeleteAccounts()) {

‎src/main/java/org/tron/core/Constant.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,11 @@ public class Constant {
5151
public static final long MAX_CPU_TIME_OF_ONE_TX = 50000; // 50 ms = 50000 us
5252
public static final long STORAGE_LIMIT_IN_ONE_TX_OF_SMART_CONTRACT = 32 * 1024 * 1024L; // 32MB
5353
public static final long SUN_PER_ENERGY = 100; // 1 us = 100 DROP = 100 * 10^-6 TRX
54-
public static final long MAX_ENERGY_IN_TX = 3000000; // ref: 1 us = 1 energy
54+
public static final long ENERGY_LIMIT_IN_CONSTANT_TX = 3000000; // ref: 1 us = 1 energy
5555
public static final long MAX_RESULT_SIZE_IN_TX = 64; // max 8 * 8 items in result
56+
public static final int PB_DEFAULT_ENERGY_LIMIT = 0;
57+
public static final long CREATOR_DEFAULT_ENERGY_LIMIT = 10_000_000;
58+
5659
public static final long MAX_CONSUME_USER_RESOURCE_PERCENT = 100L;
5760
public static final long MIN_CONSUME_USER_RESOURCE_PERCENT = 0L;
5861
public static final long ACCORD_RANGE_PERCENT = 0L;

‎src/main/java/org/tron/core/db/DynamicPropertiesStore.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,6 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking<BytesCapsule>
132132
private static final byte[] ALLOW_CREATION_OF_CONTRACTS = "ALLOW_CREATION_OF_CONTRACTS"
133133
.getBytes();
134134

135-
136135
@Autowired
137136
private DynamicPropertiesStore(@Value("properties") String dbName) {
138137
super(dbName);
@@ -782,7 +781,8 @@ public long getCreateNewAccountFeeInSystemContract() {
782781
.map(BytesCapsule::getData)
783782
.map(ByteArray::toLong)
784783
.orElseThrow(
785-
() -> new IllegalArgumentException("not found CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT"));
784+
() -> new IllegalArgumentException(
785+
"not found CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT"));
786786
}
787787

788788
public void saveCreateNewAccountBandwidthRate(long rate) {
@@ -1190,14 +1190,14 @@ public void updateNextMaintenanceTime(long blockTime) {
11901190
public void addTotalNetWeight(long amount) {
11911191
long totalNetWeight = getTotalNetWeight();
11921192
totalNetWeight += amount;
1193-
saveTotalNetWeight( totalNetWeight );
1193+
saveTotalNetWeight(totalNetWeight);
11941194
}
11951195

11961196
//The unit is trx
11971197
public void addTotalEnergyWeight(long amount) {
11981198
long totalEnergyWeight = getTotalEnergyWeight();
11991199
totalEnergyWeight += amount;
1200-
saveTotalEnergyWeight( totalEnergyWeight );
1200+
saveTotalEnergyWeight(totalEnergyWeight);
12011201
}
12021202

12031203
public void addTotalCreateAccountCost(long fee) {

‎src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.tron.common.application.TronApplicationContext;
1313
import org.tron.common.runtime.TVMTestResult;
1414
import org.tron.common.runtime.TVMTestUtils;
15+
import org.tron.common.runtime.vm.program.Program.OutOfEnergyException;
1516
import org.tron.common.runtime.vm.program.Program.OutOfResourceException;
1617
import org.tron.common.storage.DepositImpl;
1718
import org.tron.common.utils.FileUtil;
@@ -114,7 +115,7 @@ public void endlessLoopTest()
114115
long expectEnergyUsageTotal2 = feeLimit / 100;
115116
Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2);
116117
Exception exception = result.getRuntime().getResult().getException();
117-
Assert.assertTrue(exception instanceof OutOfResourceException);
118+
Assert.assertTrue((exception instanceof OutOfResourceException) || (exception instanceof OutOfEnergyException));
118119
Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(),
119120
totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100);
120121
}

0 commit comments

Comments
 (0)