Skip to content

Commit fbbcb6e

Browse files
committed
feat(freezeV2): optimize Stake2.0 code
1 parent e9bf1d8 commit fbbcb6e

File tree

18 files changed

+190
-83
lines changed

18 files changed

+190
-83
lines changed

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public boolean execute(Object result) throws ContractExeException {
5858
List<UnFreezeV2> unfrozenV2List = ownerCapsule.getUnfrozenV2List();
5959
long now = dynamicStore.getLatestBlockHeaderTimestamp();
6060
AtomicLong atomicWithdrawExpireBalance = new AtomicLong(0L);
61+
/* The triple object is defined by resource type, with left representing the pair object
62+
corresponding to bandwidth, middle representing the pair object corresponding to energy, and
63+
right representing the pair object corresponding to tron power. The pair object for each
64+
resource type, left represents resource weight, and right represents the number of unfreeze
65+
resources for that resource type. */
6166
Triple<Pair<AtomicLong, AtomicLong>, Pair<AtomicLong, AtomicLong>, Pair<AtomicLong, AtomicLong>>
6267
triple = Triple.of(
6368
Pair.of(new AtomicLong(0L), new AtomicLong(0L)),

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

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.tron.core.actuator;
22

33
import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR;
4+
import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL;
45
import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD;
56
import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION;
67
import static org.tron.protos.contract.Common.ResourceCode;
@@ -66,7 +67,8 @@ public boolean execute(Object result) throws ContractExeException {
6667
DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore();
6768
long delegateBalance = delegateResourceContract.getBalance();
6869
boolean lock = delegateResourceContract.getLock();
69-
long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract);
70+
long lockPeriod = getLockPeriod(dynamicStore.supportMaxDelegateLockPeriod(),
71+
delegateResourceContract);
7072
byte[] receiverAddress = delegateResourceContract.getReceiverAddress().toByteArray();
7173

7274
// delegate resource to receiver
@@ -155,14 +157,12 @@ public boolean validate() throws ContractValidateException {
155157

156158
long accountNetUsage = ownerCapsule.getNetUsage();
157159
if (null != this.getTx() && this.getTx().isTransactionCreate()) {
158-
accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(
159-
ownerCapsule.getBalance());
160+
accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore,
161+
ownerCapsule.getBalance());
160162
}
161163
long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double)
162164
(dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit()));
163-
164165
long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage);
165-
166166
if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) {
167167
throw new ContractValidateException(
168168
"delegateBalance must be less than or equal to available FreezeBandwidthV2 balance");
@@ -175,9 +175,7 @@ public boolean validate() throws ContractValidateException {
175175

176176
long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double)
177177
(dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit()));
178-
179178
long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage);
180-
181179
if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) {
182180
throw new ContractValidateException(
183181
"delegateBalance must be less than or equal to available FreezeEnergyV2 balance");
@@ -211,7 +209,7 @@ public boolean validate() throws ContractValidateException {
211209

212210
boolean lock = delegateResourceContract.getLock();
213211
if (lock && dynamicStore.supportMaxDelegateLockPeriod()) {
214-
long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract);
212+
long lockPeriod = getLockPeriod(true, delegateResourceContract);
215213
long maxDelegateLockPeriod = dynamicStore.getMaxDelegateLockPeriod();
216214
if (lockPeriod < 0 || lockPeriod > maxDelegateLockPeriod) {
217215
throw new ContractValidateException(
@@ -249,20 +247,20 @@ public boolean validate() throws ContractValidateException {
249247
return true;
250248
}
251249

252-
private long getLockPeriod(DynamicPropertiesStore dynamicStore,
250+
private long getLockPeriod(boolean supportMaxDelegateLockPeriod,
253251
DelegateResourceContract delegateResourceContract) {
254252
long lockPeriod = delegateResourceContract.getLockPeriod();
255-
if (dynamicStore.supportMaxDelegateLockPeriod()) {
256-
return lockPeriod == 0 ? DELEGATE_PERIOD / 3000 : lockPeriod;
253+
if (supportMaxDelegateLockPeriod) {
254+
return lockPeriod == 0 ? DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL : lockPeriod;
257255
} else {
258-
return 0;
256+
return DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL;
259257
}
260258
}
261259

262260
private void validRemainTime(ResourceCode resourceCode, long lockPeriod, long expireTime,
263261
long now) throws ContractValidateException {
264262
long remainTime = expireTime - now;
265-
if (lockPeriod * 3 * 1000 < remainTime) {
263+
if (lockPeriod * BLOCK_PRODUCED_INTERVAL < remainTime) {
266264
throw new ContractValidateException(
267265
"The lock period for " + resourceCode.name() + " this time cannot be less than the "
268266
+ "remaining time[" + remainTime + "ms] of the last lock period for "
@@ -295,11 +293,7 @@ private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boole
295293
//modify DelegatedResourceStore
296294
long expireTime = 0;
297295
if (lock) {
298-
if (dynamicPropertiesStore.supportMaxDelegateLockPeriod()) {
299-
expireTime = now + lockPeriod * 3 * 1000;
300-
} else {
301-
expireTime = now + DELEGATE_PERIOD;
302-
}
296+
expireTime = now + lockPeriod * BLOCK_PRODUCED_INTERVAL;
303297
}
304298
byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, lock);
305299
DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key);

actuator/src/main/java/org/tron/core/utils/ProposalUtil.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import static org.tron.core.Constant.DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE;
44
import static org.tron.core.Constant.DYNAMIC_ENERGY_MAX_FACTOR_RANGE;
5+
import static org.tron.core.config.Parameter.ChainConstant.ONE_YEAR_BLOCK_NUMBERS;
56

67
import org.tron.common.utils.ForkController;
78
import org.tron.core.config.Parameter.ForkBlockVersionConsts;
@@ -714,10 +715,11 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore,
714715
"Bad chain parameter id [MAX_DELEGATE_LOCK_PERIOD]");
715716
}
716717
long maxDelegateLockPeriod = dynamicPropertiesStore.getMaxDelegateLockPeriod();
717-
if (value <= maxDelegateLockPeriod || value > 10512000L) {
718+
if (value <= maxDelegateLockPeriod || value > ONE_YEAR_BLOCK_NUMBERS) {
718719
throw new ContractValidateException(
719720
"This value[MAX_DELEGATE_LOCK_PERIOD] is only allowed to be greater than "
720-
+ maxDelegateLockPeriod + " and less than or equal to 10512000 !");
721+
+ maxDelegateLockPeriod + " and less than or equal to " + ONE_YEAR_BLOCK_NUMBERS
722+
+ " !");
721723
}
722724
if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) {
723725
throw new ContractValidateException(

actuator/src/main/java/org/tron/core/utils/TransactionUtil.java

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import org.tron.core.capsule.TransactionCapsule;
4545
import org.tron.core.exception.PermissionException;
4646
import org.tron.core.exception.SignatureFormatException;
47+
import org.tron.core.store.DynamicPropertiesStore;
4748
import org.tron.protos.Protocol.Permission;
4849
import org.tron.protos.Protocol.Permission.PermissionType;
4950
import org.tron.protos.Protocol.Transaction;
@@ -222,7 +223,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) {
222223
}
223224
tswBuilder.setPermission(permission);
224225
if (trx.getSignatureCount() > 0) {
225-
List<ByteString> approveList = new ArrayList<ByteString>();
226+
List<ByteString> approveList = new ArrayList<>();
226227
long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(),
227228
Sha256Hash.hash(CommonParameter.getInstance()
228229
.isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList);
@@ -253,12 +254,19 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) {
253254
return tswBuilder.build();
254255
}
255256

256-
public static long estimateConsumeBandWidthSize(long balance) {
257-
DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder()
258-
.setLock(true)
259-
.setBalance(balance);
257+
public static long estimateConsumeBandWidthSize(DynamicPropertiesStore dps, long balance) {
258+
DelegateResourceContract.Builder builder;
259+
if (dps.supportMaxDelegateLockPeriod()) {
260+
builder = DelegateResourceContract.newBuilder()
261+
.setLock(true)
262+
.setLockPeriod(dps.getMaxDelegateLockPeriod())
263+
.setBalance(balance);
264+
} else {
265+
builder = DelegateResourceContract.newBuilder()
266+
.setLock(true)
267+
.setBalance(balance);
268+
}
260269
long builderSize = builder.build().getSerializedSize();
261-
262270
DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder()
263271
.setBalance(TRX_PRECISION);
264272
long builder2Size = builder2.build().getSerializedSize();
@@ -293,6 +301,7 @@ public static long consumeBandWidthSize(
293301
return bytesSize;
294302
}
295303

304+
// only for testing
296305
public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsule,
297306
ChainBaseManager chainBaseManager) {
298307
DelegateResourceContract.Builder builder;
@@ -320,4 +329,25 @@ public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsul
320329
return DELEGATE_COST_BASE_SIZE + addSize;
321330
}
322331

332+
// only for testing
333+
public static long estimateConsumeBandWidthSizeOld(
334+
final AccountCapsule ownerCapsule,
335+
ChainBaseManager chainBaseManager) {
336+
DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder()
337+
.setLock(true)
338+
.setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth());
339+
TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build()
340+
, ContractType.DelegateResourceContract);
341+
long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager);
342+
343+
DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder()
344+
.setBalance(TRX_PRECISION);
345+
TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build()
346+
, ContractType.DelegateResourceContract);
347+
long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager);
348+
long addSize = Math.max(size1 - size2, 0L);
349+
350+
return DELEGATE_COST_BASE_SIZE + addSize;
351+
}
352+
323353
}

actuator/src/main/java/org/tron/core/vm/program/Program.java

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
import static org.apache.commons.lang3.ArrayUtils.nullToEmpty;
1010
import static org.tron.common.utils.ByteUtil.stripLeadingZeroes;
1111
import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION;
12+
import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH;
13+
import static org.tron.protos.contract.Common.ResourceCode.ENERGY;
14+
import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER;
15+
import static org.tron.protos.contract.Common.ResourceCode.UNRECOGNIZED;
1216

1317
import com.google.protobuf.ByteString;
1418
import java.math.BigInteger;
@@ -557,7 +561,7 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit
557561
ownerCapsule.setLatestConsumeTime(now);
558562
if (ownerCapsule.getNetUsage() > 0) {
559563
bandwidthProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule,
560-
ownerCapsule.getNetUsage(), Common.ResourceCode.BANDWIDTH, now);
564+
ownerCapsule.getNetUsage(), BANDWIDTH, now);
561565
}
562566

563567
EnergyProcessor energyProcessor =
@@ -567,7 +571,7 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit
567571
ownerCapsule.setLatestConsumeTimeForEnergy(now);
568572
if (ownerCapsule.getEnergyUsage() > 0) {
569573
energyProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule,
570-
ownerCapsule.getEnergyUsage(), Common.ResourceCode.ENERGY, now);
574+
ownerCapsule.getEnergyUsage(), ENERGY, now);
571575
}
572576

573577
// withdraw expire unfrozen balance
@@ -594,9 +598,9 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit
594598
private void clearOwnerFreezeV2(AccountCapsule ownerCapsule) {
595599
ownerCapsule.clearFrozenV2();
596600
ownerCapsule.setNetUsage(0);
597-
ownerCapsule.setNewWindowSize(Common.ResourceCode.BANDWIDTH, 0);
601+
ownerCapsule.setNewWindowSize(BANDWIDTH, 0);
598602
ownerCapsule.setEnergyUsage(0);
599-
ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 0);
603+
ownerCapsule.setNewWindowSize(ENERGY, 0);
600604
ownerCapsule.clearUnfrozenV2();
601605
}
602606

@@ -2077,11 +2081,11 @@ public boolean unDelegateResource(
20772081
private Common.ResourceCode parseResourceCode(DataWord resourceType) {
20782082
switch (resourceType.intValue()) {
20792083
case 0:
2080-
return Common.ResourceCode.BANDWIDTH;
2084+
return BANDWIDTH;
20812085
case 1:
2082-
return Common.ResourceCode.ENERGY;
2086+
return ENERGY;
20832087
default:
2084-
return Common.ResourceCode.UNRECOGNIZED;
2088+
return UNRECOGNIZED;
20852089
}
20862090
}
20872091

@@ -2090,13 +2094,13 @@ private Common.ResourceCode parseResourceCodeV2(DataWord resourceType) {
20902094
byte type = resourceType.sValue().byteValueExact();
20912095
switch (type) {
20922096
case 0:
2093-
return Common.ResourceCode.BANDWIDTH;
2097+
return BANDWIDTH;
20942098
case 1:
2095-
return Common.ResourceCode.ENERGY;
2099+
return ENERGY;
20962100
case 2:
2097-
return Common.ResourceCode.TRON_POWER;
2101+
return TRON_POWER;
20982102
default:
2099-
return Common.ResourceCode.UNRECOGNIZED;
2103+
return UNRECOGNIZED;
21002104
}
21012105
} catch (ArithmeticException e) {
21022106
logger.warn("TVM ParseResourceCodeV2: invalid resource code: {}", resourceType.sValue());

actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import org.tron.core.vm.repository.Repository;
1313
import org.tron.protos.Protocol;
1414

15-
1615
public class FreezeV2Util {
1716

1817
private FreezeV2Util() {

chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package org.tron.core.db;
22

3-
import static java.lang.Math.ceil;
4-
import static java.lang.Math.round;
53
import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL;
64
import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION;
75

@@ -134,7 +132,11 @@ public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode,
134132
}
135133

136134
public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiver,
137-
long transferUsage, ResourceCode resourceCode, long now) {
135+
long transferUsage, ResourceCode resourceCode, long now) {
136+
if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) {
137+
unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now);
138+
return;
139+
}
138140
long lastOwnerTime = owner.getLastConsumeTime(resourceCode);
139141
long ownerUsage = owner.getUsage(resourceCode);
140142
// Update itself first
@@ -151,6 +153,7 @@ public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv
151153
owner.setNewWindowSize(resourceCode, this.windowSize);
152154
owner.setUsage(resourceCode, 0);
153155
owner.setLatestTime(resourceCode, now);
156+
return;
154157
}
155158
// calculate new windowSize
156159
long newOwnerWindowSize = getNewWindowSize(ownerUsage, remainOwnerWindowSize, transferUsage,
@@ -160,7 +163,7 @@ public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv
160163
owner.setLatestTime(resourceCode, now);
161164
}
162165

163-
public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver,
166+
public void unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver,
164167
long transferUsage, ResourceCode resourceCode, long now) {
165168
long lastOwnerTime = owner.getLastConsumeTime(resourceCode);
166169
long ownerUsage = owner.getUsage(resourceCode);
@@ -170,7 +173,9 @@ public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule rece
170173
// mean ownerUsage == 0 and transferUsage == 0
171174
if (newOwnerUsage == 0) {
172175
owner.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION);
173-
return newOwnerUsage;
176+
owner.setUsage(resourceCode, 0);
177+
owner.setLatestTime(resourceCode, now);
178+
return;
174179
}
175180

176181
long remainOwnerWindowSizeV2 = owner.getWindowSizeV2(resourceCode);
@@ -185,7 +190,8 @@ public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule rece
185190
newOwnerUsage);
186191
newOwnerWindowSize = Math.min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION);
187192
owner.setNewWindowSizeV2(resourceCode, newOwnerWindowSize);
188-
return newOwnerUsage;
193+
owner.setUsage(resourceCode, newOwnerUsage);
194+
owner.setLatestTime(resourceCode, now);
189195
}
190196

191197
private long getNewWindowSize(long lastUsage, long lastWindowSize, long usage,

chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.tron.core.store;
22

3+
import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL;
34
import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD;
45

56
import com.google.protobuf.ByteString;
@@ -2824,11 +2825,12 @@ public long getMaxDelegateLockPeriod() {
28242825
return Optional.ofNullable(getUnchecked(MAX_DELEGATE_LOCK_PERIOD))
28252826
.map(BytesCapsule::getData)
28262827
.map(ByteArray::toLong)
2827-
.orElse(DELEGATE_PERIOD / 3000);
2828+
.orElse(DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL);
28282829
}
28292830

28302831
public boolean supportMaxDelegateLockPeriod() {
2831-
return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / 3000) && getUnfreezeDelayDays() > 0;
2832+
return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL) &&
2833+
getUnfreezeDelayDays() > 0;
28322834
}
28332835

28342836
private static class DynamicResourceProperties {

common/src/main/java/org/tron/common/utils/JsonUtil.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55

66
public class JsonUtil {
77

8-
public static <T> T json2Obj(String jsonString, Class<T> clazz) {
9-
if (StringUtils.hasLength(jsonString) && clazz != null) {
8+
public static final <T> T json2Obj(String jsonString, Class<T> clazz) {
9+
if (!StringUtils.isEmpty(jsonString) && clazz != null) {
1010
try {
1111
ObjectMapper om = new ObjectMapper();
1212
return om.readValue(jsonString, clazz);
@@ -18,7 +18,7 @@ public static <T> T json2Obj(String jsonString, Class<T> clazz) {
1818
}
1919
}
2020

21-
public static String obj2Json(Object obj) {
21+
public static final String obj2Json(Object obj) {
2222
if (obj == null) {
2323
return null;
2424
} else {

common/src/main/java/org/tron/core/config/Parameter.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ public class ChainConstant {
7777
public static final long TRX_PRECISION = 1000_000L;
7878
public static final long DELEGATE_COST_BASE_SIZE = 275L;
7979
public static final long WINDOW_SIZE_PRECISION = 1000L;
80+
public static final long ONE_YEAR_BLOCK_NUMBERS = 10512000L;
8081
}
8182

8283
public class NodeConstant {

0 commit comments

Comments
 (0)