Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions chainbase/src/main/java/org/tron/core/db/TransactionTrace.java
Original file line number Diff line number Diff line change
Expand Up @@ -303,13 +303,20 @@ private void resetAccountUsage(AccountCapsule accountCap,
}
long currentSize = accountCap.getWindowSize(ENERGY);
long currentUsage = accountCap.getEnergyUsage();
boolean allowOptimization = dynamicPropertiesStore.allowTvmResourceOptimization();
// Drop the pre consumed frozen energy
long newArea = currentUsage * currentSize
- (mergedUsage * mergedSize - usage * size);
// If area merging happened during suicide, use the current window size
long newSize = mergedSize == currentSize ? size : currentSize;
boolean areaMerged = allowOptimization
? currentUsage > mergedUsage || mergedSize != currentSize

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allowTvmResourceOptimization() is called twice per method invocation (once for areaMerged, once for the guard before checkResetEnergyUsage). If this method reads from the dynamic properties store (a DB-backed map), that is two unnecessary lookups per call. Cache it as a local boolean at the top of each method:

boolean isOptimizationAllowed = dynamicPropertiesStore.allowTvmResourceOptimization();
boolean areaMerged = isOptimizationAllowed
    ? currentUsage > mergedUsage || mergedSize != currentSize
    : mergedSize != currentSize;
...
if (isOptimizationAllowed) {
  checkResetEnergyUsage(newUsage);
}

Same applies in resetAccountUsageV2.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — cached dynamicPropertiesStore.allowTvmResourceOptimization() in a local boolean allowOptimization variable in both resetAccountUsage and resetAccountUsageV2 to avoid the redundant lookup. Updated in c598184.

: mergedSize != currentSize;
long newSize = areaMerged ? currentSize : size;
// Calc new usage by fixed x-axes
long newUsage = max(0, newArea / newSize, dynamicPropertiesStore.disableJavaLangMath());
if (allowOptimization) {
checkResetEnergyUsage(newUsage);
}
// Reset account usage and window size
accountCap.setEnergyUsage(newUsage);
accountCap.setNewWindowSize(ENERGY, newUsage == 0 ? 0L : newSize);
Expand All @@ -320,18 +327,35 @@ private void resetAccountUsageV2(AccountCapsule accountCap,
long currentSize = accountCap.getWindowSize(ENERGY);
long currentSize2 = accountCap.getWindowSizeV2(ENERGY);
long currentUsage = accountCap.getEnergyUsage();
boolean allowOptimization = dynamicPropertiesStore.allowTvmResourceOptimization();
// Drop the pre consumed frozen energy
long newArea = currentUsage * currentSize - (mergedUsage * mergedSize - usage * size);
// If area merging happened during suicide, use the current window size
long newSize = mergedSize == currentSize ? size : currentSize;
long newSize2 = mergedSize == currentSize ? size2 : currentSize2;
boolean areaMerged = allowOptimization
? currentUsage > mergedUsage || mergedSize != currentSize
: mergedSize != currentSize;
long newSize = areaMerged ? currentSize : size;
long newSize2 = areaMerged ? currentSize2 : size2;
// Calc new usage by fixed x-axes
long newUsage = max(0, newArea / newSize, dynamicPropertiesStore.disableJavaLangMath());
if (allowOptimization) {
checkResetEnergyUsage(newUsage);
}
// Reset account usage and window size
accountCap.setEnergyUsage(newUsage);
accountCap.setNewWindowSizeV2(ENERGY, newUsage == 0 ? 0L : newSize2);
}

private void checkResetEnergyUsage(long newUsage) {
long totalEnergyCurrentLimit = dynamicPropertiesStore.getTotalEnergyCurrentLimit();
long maxUsage = totalEnergyCurrentLimit <= 0 ? 0L
: (totalEnergyCurrentLimit > Long.MAX_VALUE / 2
? Long.MAX_VALUE : totalEnergyCurrentLimit * 2);
if (newUsage > maxUsage) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When totalEnergyCurrentLimit <= 0, maxUsage is set to 0L, which means any newUsage > 0 immediately throws. This could be a subtle footgun if the store ever returns 0 (e.g. during early initialization or a misconfiguration). Consider whether the intent is really "no limit" (skip the check) or "all usage is invalid" (throw). If the intent is a safety guard, a comment explaining the invariant that makes totalEnergyCurrentLimit <= 0 impossible in practice would prevent future confusion. Otherwise, guard with a no-op:

if (totalEnergyCurrentLimit <= 0) {
  return; // limit not yet set, skip check
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping maxUsage = 0L when totalEnergyCurrentLimit <= 0 is intentional here:

  • TOTAL_ENERGY_CURRENT_LIMIT is always initialized at genesis (50,000,000,000L by default; reading an uninitialized entry throws IllegalArgumentException), so it cannot silently default to 0 during startup.
  • If governance explicitly sets TOTAL_CURRENT_ENERGY_LIMIT to 0 (or if a non-positive value were ever encountered), keeping maxUsage = 0L preserves the literal 2 * totalEnergyCurrentLimit bound (2 * 0 = 0) rather than bypassing the check or multiplying a negative value.

throw new ArithmeticException("Energy usage exceeds limit: " + newUsage);
}
}

public boolean checkNeedRetry() {
if (!needVM()) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,22 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION;
import static org.tron.protos.contract.Common.ResourceCode.ENERGY;

import com.google.protobuf.ByteString;
import java.util.Locale;
import org.junit.Test;
import org.tron.common.runtime.RuntimeImpl;
import org.tron.common.runtime.TvmTestUtils;
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.capsule.DelegatedResourceCapsule;
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.db.EnergyProcessor;
import org.tron.core.db.TransactionTrace;
import org.tron.core.store.StoreFactory;
import org.tron.core.vm.config.VMConfig;

public class Tip945VmTest extends TvmOptimizationVmTestBase {
Expand Down Expand Up @@ -282,6 +290,149 @@ private void ownEnergyWeight(byte[]... addresses) {
dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(weight);
}

@Test
public void energyMergeRetainsWindowAfterOptimization() throws Exception {
for (long cancelAllV2 : new long[]{0, 1}) {
dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(cancelAllV2);
dbManager.getDynamicPropertiesStore().saveEnergyFee(100);
dbManager.getDynamicPropertiesStore().saveTotalEnergyCurrentLimit(100_000_000L);
install(SOURCE, destroy(CALLER));
setEnergyAccount(CALLER, 10_000L * TRX_PRECISION, 50_000L, 10_000L, cancelAllV2 == 1);
setEnergyAccount(SOURCE, 10_000L * TRX_PRECISION, 100_000L, 19_400L, cancelAllV2 == 1);
ownEnergyWeight(CALLER, SOURCE);

TransactionTrace trace = executeWithFeeLimit(SOURCE, 5_000_000L);
assertSuccess(trace);
assertEquals(19_400L, trace.getReceipt().getCallerEnergyMergedWindowSize());
assertEquals(19_400L, account(CALLER).getWindowSize(ENERGY));
finish(trace);

assertTrue(account(CALLER).getWindowSize(ENERGY) >= 19_400L);
}
}

@Test
public void originEnergyMergeRetainsWindowAfterOptimization() throws Exception {
dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1);
dbManager.getDynamicPropertiesStore().saveEnergyFee(100);
dbManager.getDynamicPropertiesStore().saveTotalEnergyCurrentLimit(100_000_000L);
install(THIRD, "00");
install(SOURCE, destroy(THIRD));
install(OUTER, outer(SOURCE, false), THIRD, 0L, 50_000L);
setEnergyAccount(CALLER, 10_000L * TRX_PRECISION, 0L, 0L, true);
setEnergyAccount(THIRD, 10_000L * TRX_PRECISION, 50_000L, 10_000L, true);
setEnergyAccount(SOURCE, 10_000L * TRX_PRECISION, 100_000L, 19_400L, true);
ownEnergyWeight(CALLER, THIRD, SOURCE);

TransactionTrace trace = executeWithFeeLimit(OUTER, 5_000_000L);
assertSuccess(trace);
assertEquals(19_400L, trace.getReceipt().getOriginEnergyMergedWindowSize());
assertEquals(19_400L, account(THIRD).getWindowSize(ENERGY));
finish(trace);

assertTrue(account(THIRD).getWindowSize(ENERGY) >= 19_400L);
}

@Test
public void undelegatePreservesCallerWindowAfterOptimization() throws Exception {
dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1);
dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1);
dbManager.getDynamicPropertiesStore().saveEnergyFee(100);
dbManager.getDynamicPropertiesStore().saveTotalEnergyCurrentLimit(100_000_000L);
String undelegateCode = pushAddress(CALLER)
+ "63" + String.format(Locale.ROOT, "%08x", (int) TRX_PRECISION)
+ push(1) + "df5000";
install(SOURCE, undelegateCode);
setEnergyAccount(CALLER, 10_000L * TRX_PRECISION, 10_000L, 10_000L, true);
AccountCapsule callerCap = account(CALLER);
callerCap.addAcquiredDelegatedFrozenV2BalanceForEnergy(10L * TRX_PRECISION);
save(callerCap);
AccountCapsule sourceCap = account(SOURCE);
sourceCap.addDelegatedFrozenV2BalanceForEnergy(10L * TRX_PRECISION);
save(sourceCap);
byte[] key = DelegatedResourceCapsule.createDbKeyV2(SOURCE, CALLER, false);
DelegatedResourceCapsule delegated = new DelegatedResourceCapsule(
ByteString.copyFrom(SOURCE), ByteString.copyFrom(CALLER));
delegated.addFrozenBalanceForEnergy(10L * TRX_PRECISION, 0L);
dbManager.getDelegatedResourceStore().put(key, delegated);
ownEnergyWeight(CALLER, SOURCE);

TransactionTrace trace = executeWithFeeLimit(SOURCE, 5_000_000L);
assertSuccess(trace);
long mergedSize = trace.getReceipt().getCallerEnergyMergedWindowSize();
assertTrue(mergedSize > 20_000L);
assertTrue(account(CALLER).getEnergyUsage() < trace.getReceipt().getCallerEnergyMergedUsage());
assertEquals(mergedSize, account(CALLER).getWindowSize(ENERGY));
finish(trace);

assertTrue(trace.getReceipt().getEnergyUsage() > 0);
assertTrue(account(CALLER).getWindowSize(ENERGY) < 20_000L);
}

@Test
public void resetAccountUsageValidatesEnergyLimitAfterOptimization() throws Exception {
long totalLimit = 100_000_000L;
long cap = totalLimit * 2;
long overLimitUsage = 250_000_000L;
long withinCapUsage = 150_000_000L;
install(SOURCE, "60015000");

for (long cancelAllV2 : new long[]{0, 1}) {
for (long enabled : new long[]{0, 1}) {
VMConfig.initAllowTvmResourceOptimization(enabled);
dbManager.getDynamicPropertiesStore().saveAllowTvmResourceOptimization(enabled);
dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(cancelAllV2);
dbManager.getDynamicPropertiesStore().saveEnergyFee(100);
dbManager.getDynamicPropertiesStore().saveTotalEnergyCurrentLimit(totalLimit);

for (long initialUsage : new long[]{overLimitUsage, cap, withinCapUsage}) {
setEnergyAccount(CALLER, 10_000L * TRX_PRECISION, initialUsage, 20_000L,
cancelAllV2 == 1);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The else branch asserts assertEquals(initialUsage, account(CALLER).getEnergyUsage()) after finishing a trace that runs a real contract. This passes only if the trivial bytecode "60015000" leaves CALLER's stored energy usage unchanged by resetAccountUsage. That is a non-obvious postcondition. A short comment explaining why (e.g. the contract consumes no stake-based energy so newUsage rounds back to initialUsage) would make the assertion self-documenting and prevent false confidence if the test helper is reused with a different contract.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point — initialUsage (150_000_000L / 200_000_000L) is well above CALLER's frozen energy limit (from 10,000 TRX), so leftFrozenEnergy is 0 and the "60015000" execution pays its small bill entirely in TRX without consuming staked energy, leaving CALLER's stored energyUsage unchanged at initialUsage. Keeping the test minimal as-is since this fixture only runs that trivial bytecode — thanks for the careful review!

ownEnergyWeight(CALLER);

TransactionTrace trace = executeWithFeeLimit(SOURCE, 1_000_000L);
assertSuccess(trace);
if (enabled == 1 && initialUsage > cap) {
assertThrows(ArithmeticException.class, () -> finish(trace));
} else {
finish(trace);
assertEquals(initialUsage, account(CALLER).getEnergyUsage());
assertEquals(20_000L, account(CALLER).getWindowSize(ENERGY));
}
}
}
}
}

private void setEnergyAccount(byte[] address, long frozenEnergy, long usage, long windowSlots,
boolean windowV2) {
AccountCapsule cap = account(address);
cap.clearFrozenV2();
cap.addFrozenBalanceForEnergyV2(frozenEnergy);
cap.setEnergyUsage(usage);
cap.setLatestConsumeTimeForEnergy(
EnergyProcessor.getHeadSlot(dbManager.getDynamicPropertiesStore()));
if (windowV2) {
cap.setNewWindowSizeV2(ENERGY, windowSlots * 1_000L);
} else {
cap.setNewWindowSize(ENERGY, windowSlots);
cap.setWindowOptimized(ENERGY, false);
}
save(cap);
}

private TransactionTrace executeWithFeeLimit(byte[] contract, long feeLimit) throws Exception {
TransactionCapsule tx = new TransactionCapsule(
TvmTestUtils.generateTriggerSmartContractAndGetTransaction(
CALLER, contract, new byte[0], 0, feeLimit));
TransactionTrace trace =
new TransactionTrace(tx, StoreFactory.getInstance(), new RuntimeImpl());
tx.setTrxTrace(trace);
trace.init(null);
trace.exec();
return trace;
}

private void assertZeroEnergy(TransactionTrace trace) {
assertSuccess(trace);
assertEquals(0, trace.getReceipt().getEnergyUsageTotal());
Expand Down
Loading