TIP-945: Optimize TVM Resource Processing
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 25/100
Research direction
The proposal names Program.voteWitness() in actuator/src/main/java/org/tron/core/vm/program/Program.java, Parameter.java, AccountCapsule.java, and FreezeBalanceV2Processor.java as relevant entry points. Read those implementations and the linked TIP-944, then trace the self-destruct Stake 2.0 transfer and its tests in java-tron. Done means the activation-gated validation order, per-account weight deltas, and rollback behavior match the specification across the listed cases.
Written by the indexing model from the issue text.
Description
tip: 945
title: Optimize TVM Resource Processing
author: [email protected]
discussions-to: https://github.com/tronprotocol/tips/issues/945
status: Draft
type: Standards Track
category: VM
created: 2026-10-27
Simple Summary
Improve TVM resource-processing efficiency and maintain consistent stake-weight accounting across account-state transitions.
Abstract
This proposal improves bounded voting-input validation, operation-local stake weights, zero-Energy finalization, and CPU-deadline enforcement after child bytecode returns. The changes are activated through a new on-chain parameter and preserve the independently selected resource-accounting rules.
Motivation
TVM execution should validate bounded inputs efficiently and apply consistent resource-accounting rules.
This proposal improves voting-input validation and stake-weight updates within the existing execution framework. A zero-usage billing return must not discard restored reservation state. A child frame that crosses the CPU deadline in its final opcode must be checked before the parent proceeds with its result.
Specification
This proposal introduces a new on-chain parameter, ALLOW_TVM_RESOURCE_OPTIMIZATION, to enable the changes described below.
Vote-entry limit and validation order
The supplied entry count is bounded by Parameter.ChainConstant.MAX_VOTE_NUMBER, currently 30. This proposal does not change that limit. Count entries before merging duplicate witnesses or removing zero-vote entries; empty arrays retain their existing behavior.
After activation, the checks in Program.voteWitness execute in this order:
- Check each in-memory array-length header against its corresponding supplied length, checking the witness-array header first and the amount-array header second. A mismatch follows the existing
BytecodeExecutionExceptionpath. - Check that the two supplied lengths are equal. A mismatch returns failure (
0), marks the internal transaction rejected if one was recorded, leaves itsextraempty, and applies no vote-state update. The existing nonce increment is retained. - Check the common supplied length against
MAX_VOTE_NUMBER. If it exceeds the limit, return failure (0), mark the internal transaction rejected if one was recorded, leave itsextraempty, and apply no vote-state update. The existing nonce increment is retained.
The first failing check determines the result. Operand conversion and normal VM static-context, memory, and energy checks continue to apply as before. The instruction's energy-cost formula is unchanged. Normal instruction and memory-expansion Energy charges are assessed before the equality- or count-check rejection; neither rejection itself reverts the enclosing call or consumes all remaining Energy.
The oversized-count branch MUST reject before copying array payloads, decoding individual entries, constructing vote objects, or serializing vote JSON. Avoiding this per-entry work is a required execution-order constraint, rather than an optional implementation suggestion. The processor-level count validation is retained.
The existing entry point and failure paths are defined in Program.voteWitness(). Valid inputs proceed through their existing processing rules.
Per-account stake weights
Let P = TRX_PRECISION = 1,000,000 sun per TRX, as defined by Parameter.ChainConstant.TRX_PRECISION. For each account a:
| Stake type | Balance B_r(a), in sun |
Global weight |
|---|---|---|
| BANDWIDTH | Own active Stake 2.0 BANDWIDTH balance plus active delegated-out Stake 2.0 BANDWIDTH balance | TotalNetWeight |
| ENERGY | Own active Stake 2.0 ENERGY balance plus active delegated-out Stake 2.0 ENERGY balance | TotalEnergyWeight |
| TRON_POWER | Own active Stake 2.0 TRON_POWER balance | TotalTronPowerWeight |
Active delegated-out balances remain included while accounted to that stake owner, even when the resources are used by another account. Include any such existing beneficiary balance. Acquired delegated resources, Stake 1.0 balances, liquid TRX, and pending or withdrawn unfreeze balances are excluded.
For every account and stake type, calculate:
W_r(a) = floor(B_r(a) / P)
Use non-negative integer division. Calculate each account's weight first, then sum those weights; do not combine different accounts' balances before division.
These definitions follow AccountCapsule.getFrozenV2BalanceWithDelegated() and the existing FreezeBalanceV2Processor weight calculations. This proposal does not relax the existing self-destruct prerequisites concerning the source account's delegated-out stake.
Transfer boundaries and global updates
Let A be the set of distinct source and actual beneficiary accounts participating in the self-destruct Stake 2.0 transfer.
- Take
beforefrom the current execution state immediately before the transfer's first Stake 2.0 balance mutation. - Take
afterafter completing all corresponding beneficiary credits and source balance clearing for that transfer. - Calculate every account's
afterweight from its state immediately after this transfer. A source with no remaining eligible Stake 2.0 balance contributes zero whether retained or scheduled for deletion. A deletion marker alone must not override this operation-local snapshot. - Count an account once even if it appears in both roles. A branch that performs no Stake 2.0 transfer applies no transfer-related adjustment.
For each stake type r, apply:
delta_r = sum(W_r(a, after) for a in A)
- sum(W_r(a, before) for a in A)
totalWeight_r += delta_r
Apply the delta once with the account-state updates. Subsequent physical account deletion must not apply the same adjustment again. Before/after values refer to the execution state for that operation, rather than the transaction's initial state; sequential operations therefore use the state produced by preceding operations.
Existing feature prerequisites and self-destruct beneficiary/account-retention semantics remain unchanged. Account balances and global weights commit or roll back together.
Normative weight examples
For one stake type, the following balances are in sun; transfers move the source's entire eligible balance to a distinct actual beneficiary, with all existing prerequisites satisfied. Other stake types are unchanged.
| Source / beneficiary before | Source / beneficiary after | Sum of per-account weights before / after | Required delta |
|---|---|---|---|
1,600,000 / 2,300,000 |
0 / 3,900,000 |
3 / 3 |
0 |
1,600,000 / 2,400,000 |
0 / 4,000,000 |
3 / 4 |
+1 |
1,600,000 / 2,600,000 |
0 / 4,200,000 |
3 / 4 |
+1 |
In the last row, a pre-transfer global weight G becomes G + 1. Repeating the operation from the emptied source adds zero; physical source deletion adds zero. An enclosing revert restores both original balances and G. An existing offset is preserved: if G = 2, the result is 3, while the per-account sum is 4.
For BANDWIDTH or ENERGY, a beneficiary with 600,000 owned plus 600,000 delegated-out balance contributes weight 1 before receipt. Receiving 1,600,000 yields weight 2; the source changes from weight 1 to 0, so the delta is 0.
Resolve the actual beneficiary before applying these examples. A retained-source self-beneficiary branch that performs no transfer leaves balances and weights unchanged. If the existing deletion branch redirects stake to the black-hole account, use that account's actual before/after balances; do not assume its initial balance is zero. Distinct accounts are counted once.
Zero-Energy finalization and window restoration
Stake 2.0 execution temporarily reserves frozen Energy and records the pre-reservation and merged usage/window values for the caller and, where applicable, the contract's origin account. Successful execution already removes that temporary reservation using the existing TransactionTrace.resetAccountUsage() or resetAccountUsageV2() formulas before actual Energy billing.
When this proposal is active, Stake 2.0 is enabled in the transaction-finalization chain-store context, execution has neither an exception nor a revert, and total transaction Energy usage is zero, the restored account usage and window MUST be persisted even though the existing Energy-billing routine returns early. In java-tron, the billing early-return condition is energyUsageTotal <= 0; this rule concerns zero usage for valid nonnegative receipts and does not authorize negative usage.
Apply the following order and account boundaries:
- Load the current caller and origin account states at finalization, after successful execution's state updates.
- Restore the existing origin only when it is distinct from the caller, using its recorded pre-reservation and merged usage/window values. Restore the caller using its own recorded values.
- Before entering the zero-usage billing return path, persist the restored caller and any restored distinct origin in the transaction's normal state context. When caller and origin are the same address, persist the restored caller once; do not overwrite it with a separately loaded, unmodified origin object. An absent origin remains absent.
- Continue through the existing receipt and billing rules, including the receipt's normalization of actual origin Energy usage. This rule adds no Energy charge or fee.
The existing restoration arithmetic is retained. It removes only the temporary reservation's contribution from the current usage/window state; it MUST NOT replace an account wholesale with its pre-execution state or undo real changes made during execution, such as usage/window merging through SELFDESTRUCT. A prior nonzero usage balance is preserved according to those restoration and recovery rules, rather than reset to zero merely because this transaction used no Energy.
Preserve the existing window representation selected by ALLOW_CANCEL_ALL_UNFREEZE_V2: use the legacy window restoration when disabled and the precision-scaled V2 restoration when active. Preserve the existing choice of the pre-reservation versus current window when execution changed the window. If restored usage is zero, retain the restoration routine's zero stored-window convention and the account accessors' default-window interpretation.
For a fixed time slot with no other usage/window changes, the regression examples restore usage 1,000 and stored legacy window 7,200, or usage 1,000 and stored optimized window 7,200,321, after a zero-Energy execution. The same rules apply to a distinct origin; caller/origin aliasing must produce the same single-account result.
This addition is limited to successful zero-usage finalization. Positive-Energy transactions continue through their existing restoration and billing path. Exceptions and reverts retain their existing rollback and billing behavior and do not enter this new persistence branch. Disabling this proposal or Stake 2.0 preserves existing finalization behavior. No historical usage or window repair is performed at activation.
Reference implementation: TransactionTrace.pay() and its restoration helpers and ReceiptCapsule.payEnergyBill().
CPU deadlines after child bytecode execution
When this proposal is active, a parent frame MUST invoke the existing CPU-deadline checker after child bytecode execution returns normally for CALL, CALLTOKEN, CALLCODE, DELEGATECALL, STATICCALL, CREATE or CREATE2. This requirement is independent of Stake 2.0, TIP-944 and the separately activated top-level last-operation check; existing opcode-availability prerequisites still apply.
The check MUST occur before:
- Merging the child's trace or execution result into the parent.
- Adopting the child's nonce or committing its repository into the parent.
- Completing the normal success/failure stack result, copying return data or refunding unused child Energy.
- For CREATE/CREATE2, processing returned deployment code and its storage cost.
Use the existing inherited execution deadline. This proposal introduces no new per-child time budget, deadline computation or instruction Energy-cost schedule. Retain the checker's existing applicability and exemptions, including java-tron's debug and solidity-node exemptions. Where applicable, the existing strict current-time-greater-than-deadline comparison determines expiry.
If the checker reports expiry, raise the existing OutOfTimeException in the parent and propagate it through the existing OUT_OF_TIME handling. Do not convert this expiry into an ordinary failed child call/create that pushes zero and allows the parent to continue. Do not merge or commit the child after the check has failed. Earlier parent bookkeeping, transaction-state rollback, internal-transaction rejection and consumption of remaining Energy follow the existing timeout path.
The check precedes interpretation of a returned child's success, revert or recorded exception, so a reported expiry follows the timeout path even when that returned child result would otherwise be handled as failure or revert. If child execution itself throws a timeout, existing exception propagation already applies.
With an unexpired deadline, retain existing child-result handling. Branches that do not execute child bytecode, such as empty-code calls, precompiled-contract calls and early depth/balance failures, do not acquire this additional post-bytecode check. Existing checks applicable to those branches remain in force. Before activation, existing checks remain in force without this new boundary check.
This closes the case where a child's final opcode crosses the deadline after its last pre-opcode check and returns control to a parent that would otherwise proceed with its result.
Reference implementation: CREATE/CREATE2 child return, CALL-family child return, CPU-deadline checker, and VM timeout propagation.
Local VM state
Implementations may harden local cache hashing with process-local seeds. Byte-based key equality, lookup/update/commit semantics, and persisted key bytes MUST remain unchanged. Local seeds and cache iteration order must not determine protocol state transitions.
Independent activation
This proposal and TIP-944 are independently activated. Each applies only when its own parameter is active, while other independently activated protocol changes continue to apply. When both are active, the oversized-count branch returns before TIP-944's voting initialization, leaving oldTronPower unchanged. Other voting inputs remain subject to any independently activated voting-power rules.
Rationale
Earlier validation improves execution efficiency. Consistent accounting across account-state transitions preserves the resource model's established weight-calculation rules. Persisting zero-usage restoration removes the temporary reservation without changing billing formulas. Checking the inherited deadline at child-return boundaries closes the final-opcode timing gap using the existing timeout and rollback rules.
Backwards Compatibility
This proposal changes consensus-relevant execution and requires coordinated activation.
Before activation, existing validation order and execution behavior are preserved. The changes apply to subsequent execution and do not introduce historical weight reconciliation.
Before activation, existing zero-Energy finalization, repository indexing, and post-child execution checks are preserved. The zero-Energy finalization change additionally requires Stake 2.0. The child-return deadline check does not require Stake 2.0 or the separate top-level last-operation check. Existing opcode prerequisites and independently activated resource-hardening and window rules remain applicable; TIP-944 is not a prerequisite. Activation introduces no historical usage/window rewrite.
Any pre-existing offset in global weights is retained at activation. Subsequent correctly accounted per-account deltas do not, by themselves, reconcile that offset. Historical reconciliation, if required, needs a separately specified consensus change.
Test Cases
- Entry counts
0,30, and31; array-header and supplied-length mismatches and their priority. - Supplied-length mismatch and oversized-count return value, nonce, rejected internal transaction, empty extra, and absence of per-entry processing; unchanged pre-activation handling.
- Per-account rounding for all three stake types, including beneficiary delegated-out balances and excluded balance categories.
- Operation-local snapshots independent of deletion markers; distinct-account handling, retained and scheduled-for-deletion sources, sequential transfers, and no-transfer branches.
- All four activation combinations with TIP-944, including the ordering of early rejection and voting initialization.
- Atomic updates, rollback, preservation of pre-existing global-weight offsets, and preservation of pre-activation behavior.
- Successful zero-Energy finalization with caller/origin aliasing, a distinct existing origin, or an absent origin; nonzero pre-existing usage; both legacy and precision-scaled window representations; and the zero stored-window convention.
- Restoration and persistence order, preservation of genuine execution state and existing restoration arithmetic, and unchanged disabled, positive-Energy, exception and revert paths.
- Post-child checks for CALL, CALLTOKEN, CALLCODE, DELEGATECALL, STATICCALL, CREATE and CREATE2 with expired/unexpired deadlines and parameter on/off; check ordering before result/trace/nonce merging, child-state commit, return-data handling, success-stack results and Energy refunds.
- Expiry after a returned child success, revert or recorded failure; an already-propagating child timeout; existing checker exemptions; and unchanged branches without child bytecode. Parent execution must not continue through an ordinary zero return after the added checker reports expiry.
- Cache indexing preserves account/storage results across seeds and legacy/optimized modes.
Implementation
The java-tron implementation uses seeded local cache hashing behind this parameter, preserving the existing full-input hash for longer keys.
Precompiled-contract execution releases transient repository and result references on completion, including failed returns and exceptions. This local lifecycle cleanup applies independently of this parameter and introduces no persistent-state format change.
See java-tron PR #7069 for the implementation. Related regressions are Tip945VmTest, and ProgramChildDeadlineTest.
Copyright
Copyright and related rights waived via CC0.
- Dominant language
- No language data
- Stars
- 341
- Forks
- 347
- PR merge metrics
- No merged PRs in 30d
Getting set up
This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from tronprotocol/tips
-
Difficulty 1/5 Under an hour Newbie friendliness 68/100
tronprotocol/tips#950 · 2 comments ·
-
Difficulty 5/5 Over a week Newbie friendliness 25/100
tronprotocol/tips#944 · 6 comments ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 35/100
tronprotocol/tips#941 · 5 comments ·
-
Difficulty 5/5 Over a week Newbie friendliness 25/100
tronprotocol/tips#938 · 15 comments ·
-
Difficulty 5/5 Over a week Newbie friendliness 35/100
tronprotocol/tips#937 · 7 comments ·
All issues in tronprotocol/tips
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 79/100
hurttlocker/o8#6535 ·
-
area: backend bug priority: low
Difficulty 2/5 1-3 hours Newbie friendliness 92/100
snapotter-hq/SnapOtter#4856 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 64/100
-
vLLM metrics adapter tests start the adapter twice and race on its request countersPossibly taken @bhargavchintam claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
llm-d/llm-d-inference-sim#933 ·
Maintainers usually reply within 2 days