diff --git a/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java index 527c88115ac..048f703e9f7 100755 --- a/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java @@ -58,6 +58,11 @@ public boolean execute(Object result) throws ContractExeException { List unfrozenV2List = ownerCapsule.getUnfrozenV2List(); long now = dynamicStore.getLatestBlockHeaderTimestamp(); AtomicLong atomicWithdrawExpireBalance = new AtomicLong(0L); + /* The triple object is defined by resource type, with left representing the pair object + corresponding to bandwidth, middle representing the pair object corresponding to energy, and + right representing the pair object corresponding to tron power. The pair object for each + resource type, left represents resource weight, and right represents the number of unfreeze + resources for that resource type. */ Triple, Pair, Pair> triple = Triple.of( Pair.of(new AtomicLong(0L), new AtomicLong(0L)), diff --git a/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java index c54c00b5697..6725bc349b9 100755 --- a/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java @@ -1,11 +1,14 @@ package org.tron.core.actuator; import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.protos.contract.Common.ResourceCode; import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.core.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -64,7 +67,8 @@ public boolean execute(Object result) throws ContractExeException { DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); long delegateBalance = delegateResourceContract.getBalance(); boolean lock = delegateResourceContract.getLock(); - long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract); + long lockPeriod = getLockPeriod(dynamicStore.supportMaxDelegateLockPeriod(), + delegateResourceContract); byte[] receiverAddress = delegateResourceContract.getReceiverAddress().toByteArray(); // delegate resource to receiver @@ -143,7 +147,7 @@ public boolean validate() throws ContractValidateException { long delegateBalance = delegateResourceContract.getBalance(); if (delegateBalance < TRX_PRECISION) { - throw new ContractValidateException("delegateBalance must be more than 1TRX"); + throw new ContractValidateException("delegateBalance must be greater than or equal to 1 TRX"); } switch (delegateResourceContract.getResource()) { @@ -153,22 +157,15 @@ public boolean validate() throws ContractValidateException { long accountNetUsage = ownerCapsule.getNetUsage(); if (null != this.getTx() && this.getTx().isTransactionCreate()) { - accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, - chainBaseManager); + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore, + ownerCapsule.getBalance()); } long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); - - long remainNetUsage = netUsage - - ownerCapsule.getFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); - - remainNetUsage = Math.max(0, remainNetUsage); - - if (ownerCapsule.getFrozenV2BalanceForBandwidth() - remainNetUsage < delegateBalance) { + long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage); + if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) { throw new ContractValidateException( - "delegateBalance must be less than available FreezeBandwidthV2 balance"); + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance"); } } break; @@ -178,17 +175,10 @@ public boolean validate() throws ContractValidateException { long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) (dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); - - long remainEnergyUsage = energyUsage - - ownerCapsule.getEnergyFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); - - remainEnergyUsage = Math.max(0, remainEnergyUsage); - - if (ownerCapsule.getFrozenV2BalanceForEnergy() - remainEnergyUsage < delegateBalance) { + long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage); + if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) { throw new ContractValidateException( - "delegateBalance must be less than available FreezeEnergyV2 balance"); + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance"); } } break; @@ -219,7 +209,7 @@ public boolean validate() throws ContractValidateException { boolean lock = delegateResourceContract.getLock(); if (lock && dynamicStore.supportMaxDelegateLockPeriod()) { - long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract); + long lockPeriod = getLockPeriod(true, delegateResourceContract); long maxDelegateLockPeriod = dynamicStore.getMaxDelegateLockPeriod(); if (lockPeriod < 0 || lockPeriod > maxDelegateLockPeriod) { throw new ContractValidateException( @@ -257,20 +247,20 @@ public boolean validate() throws ContractValidateException { return true; } - private long getLockPeriod(DynamicPropertiesStore dynamicStore, + private long getLockPeriod(boolean supportMaxDelegateLockPeriod, DelegateResourceContract delegateResourceContract) { long lockPeriod = delegateResourceContract.getLockPeriod(); - if (dynamicStore.supportMaxDelegateLockPeriod()) { - return lockPeriod == 0 ? DELEGATE_PERIOD / 3000 : lockPeriod; + if (supportMaxDelegateLockPeriod) { + return lockPeriod == 0 ? DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL : lockPeriod; } else { - return 0; + return DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL; } } private void validRemainTime(ResourceCode resourceCode, long lockPeriod, long expireTime, long now) throws ContractValidateException { long remainTime = expireTime - now; - if (lockPeriod * 3 * 1000 < remainTime) { + if (lockPeriod * BLOCK_PRODUCED_INTERVAL < remainTime) { throw new ContractValidateException( "The lock period for " + resourceCode.name() + " this time cannot be less than the " + "remaining time[" + remainTime + "ms] of the last lock period for " @@ -303,11 +293,7 @@ private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boole //modify DelegatedResourceStore long expireTime = 0; if (lock) { - if (dynamicPropertiesStore.supportMaxDelegateLockPeriod()) { - expireTime = now + lockPeriod * 3 * 1000; - } else { - expireTime = now + DELEGATE_PERIOD; - } + expireTime = now + lockPeriod * BLOCK_PRODUCED_INTERVAL; } byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, lock); DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key); diff --git a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java index 0cfd981217f..421b4e3013a 100755 --- a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java @@ -189,7 +189,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("frozenBalance must be positive"); } if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("frozenBalance must be more than 1TRX"); + throw new ContractValidateException("frozenBalance must be greater than or equal to 1 TRX"); } int frozenCount = accountCapsule.getFrozenCount(); @@ -197,7 +197,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("frozenCount must be 0 or 1"); } if (frozenBalance > accountCapsule.getBalance()) { - throw new ContractValidateException("frozenBalance must be less than accountBalance"); + throw new ContractValidateException("frozenBalance must be less than or equal to accountBalance"); } long frozenDuration = freezeBalanceContract.getFrozenDuration(); diff --git a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java index 90b03e43e1a..f0e5505be9c 100755 --- a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java @@ -54,8 +54,8 @@ public boolean execute(Object result) throws ContractExeException { accountCapsule.initializeOldTronPower(); } - long newBalance = accountCapsule.getBalance() - freezeBalanceV2Contract.getFrozenBalance(); long frozenBalance = freezeBalanceV2Contract.getFrozenBalance(); + long newBalance = accountCapsule.getBalance() - frozenBalance; switch (freezeBalanceV2Contract.getResource()) { case BANDWIDTH: @@ -133,11 +133,11 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("frozenBalance must be positive"); } if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("frozenBalance must be more than 1TRX"); + throw new ContractValidateException("frozenBalance must be greater than or equal to 1 TRX"); } if (frozenBalance > accountCapsule.getBalance()) { - throw new ContractValidateException("frozenBalance must be less than accountBalance"); + throw new ContractValidateException("frozenBalance must be less than or equal to accountBalance"); } switch (freezeBalanceV2Contract.getResource()) { diff --git a/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java index a99d462b61c..79a09664180 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ArrayUtils; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; @@ -144,9 +143,8 @@ public boolean execute(Object result) throws ContractExeException { long now = chainBaseManager.getHeadSlot(); if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { - ownerCapsule.setNetUsage(processor.unDelegateIncrease(ownerCapsule, receiverCapsule, - transferUsage, BANDWIDTH, now)); - ownerCapsule.setLatestConsumeTime(now); + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, + transferUsage, BANDWIDTH, now); } } break; @@ -160,9 +158,7 @@ public boolean execute(Object result) throws ContractExeException { long now = chainBaseManager.getHeadSlot(); if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { - ownerCapsule.setEnergyUsage(processor.unDelegateIncrease(ownerCapsule, receiverCapsule, - transferUsage, ENERGY, now)); - ownerCapsule.setLatestConsumeTimeForEnergy(now); + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, transferUsage, ENERGY, now); } } break; @@ -240,7 +236,7 @@ public boolean validate() throws ContractValidateException { } byte[] receiverAddress = unDelegateResourceContract.getReceiverAddress().toByteArray(); - if (ArrayUtils.isEmpty(receiverAddress) || !DecodeUtil.addressValid(receiverAddress)) { + if (!DecodeUtil.addressValid(receiverAddress)) { throw new ContractValidateException("Invalid receiverAddress"); } if (Arrays.equals(receiverAddress, ownerAddress)) { diff --git a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java index 45b05ec8bec..fb41c97f7ed 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java @@ -11,6 +11,8 @@ import com.google.common.collect.Lists; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; + +import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -365,19 +367,23 @@ private void updateVote(AccountCapsule accountCapsule, } // Update Owner Voting - votesCapsule.clearNewVotes(); + List addVotes = new ArrayList<>(); for (Vote vote : accountCapsule.getVotesList()) { long newVoteCount = (long) ((double) vote.getVoteCount() / totalVote * ownedTronPower / TRX_PRECISION); if (newVoteCount > 0) { - votesCapsule.addNewVotes(vote.getVoteAddress(), newVoteCount); + Vote newVote = Vote.newBuilder() + .setVoteAddress(vote.getVoteAddress()) + .setVoteCount(newVoteCount) + .build(); + addVotes.add(newVote); } } + votesCapsule.clearNewVotes(); + votesCapsule.addAllNewVotes(addVotes); votesStore.put(ownerAddress, votesCapsule); accountCapsule.clearVotes(); - for (Vote vote : votesCapsule.getNewVotes()) { - accountCapsule.addVotes(vote.getVoteAddress(), vote.getVoteCount()); - } + accountCapsule.addAllVotes(addVotes); } } \ No newline at end of file diff --git a/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java b/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java index 0c547d2b5a3..fd71ebf1404 100755 --- a/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java @@ -125,8 +125,8 @@ private long getTotalWithdrawUnfreeze(List unfrozenV2List, long now) } private List getTotalWithdrawList(List unfrozenV2List, long now) { - return unfrozenV2List.stream().filter(unfrozenV2 -> (unfrozenV2.getUnfreezeAmount() > 0 - && unfrozenV2.getUnfreezeExpireTime() <= now)).collect(Collectors.toList()); + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); } private List getRemainWithdrawList(List unfrozenV2List, long now) { diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 0e0cc81446c..0f55bbae9b7 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -2,6 +2,7 @@ import static org.tron.core.Constant.DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE; import static org.tron.core.Constant.DYNAMIC_ENERGY_MAX_FACTOR_RANGE; +import static org.tron.core.config.Parameter.ChainConstant.ONE_YEAR_BLOCK_NUMBERS; import org.tron.common.utils.ForkController; import org.tron.core.config.Parameter.ForkBlockVersionConsts; @@ -714,10 +715,11 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, "Bad chain parameter id [MAX_DELEGATE_LOCK_PERIOD]"); } long maxDelegateLockPeriod = dynamicPropertiesStore.getMaxDelegateLockPeriod(); - if (value <= maxDelegateLockPeriod || value > 10512000L) { + if (value <= maxDelegateLockPeriod || value > ONE_YEAR_BLOCK_NUMBERS) { throw new ContractValidateException( "This value[MAX_DELEGATE_LOCK_PERIOD] is only allowed to be greater than " - + maxDelegateLockPeriod + " and less than or equal to 10512000 !"); + + maxDelegateLockPeriod + " and less than or equal to " + ONE_YEAR_BLOCK_NUMBERS + + " !"); } if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) { throw new ContractValidateException( diff --git a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index 462a80fa600..7044564b1e1 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -44,6 +44,7 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.exception.PermissionException; import org.tron.core.exception.SignatureFormatException; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Permission; import org.tron.protos.Protocol.Permission.PermissionType; import org.tron.protos.Protocol.Transaction; @@ -222,7 +223,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { } tswBuilder.setPermission(permission); if (trx.getSignatureCount() > 0) { - List approveList = new ArrayList(); + List approveList = new ArrayList<>(); long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(), Sha256Hash.hash(CommonParameter.getInstance() .isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList); @@ -253,56 +254,24 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { return tswBuilder.build(); } - public static long consumeBandWidthSize( - final TransactionCapsule transactionCapsule, - ChainBaseManager chainBaseManager) { - long bytesSize; - - boolean supportVM = chainBaseManager.getDynamicPropertiesStore().supportVM(); - if (supportVM) { - bytesSize = transactionCapsule.getInstance().toBuilder().clearRet().build().getSerializedSize(); - } else { - bytesSize = transactionCapsule.getSerializedSize(); - } - - List contracts = transactionCapsule.getInstance().getRawData().getContractList(); - for (Transaction.Contract contract : contracts) { - if (contract.getType() == Contract.ContractType.ShieldedTransferContract) { - continue; - } - if (supportVM) { - bytesSize += Constant.MAX_RESULT_SIZE_IN_TX; - } - } - - return bytesSize; - } - - public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsule, - ChainBaseManager chainBaseManager) { + public static long estimateConsumeBandWidthSize(DynamicPropertiesStore dps, long balance) { DelegateResourceContract.Builder builder; - if (chainBaseManager.getDynamicPropertiesStore().supportMaxDelegateLockPeriod()) { + if (dps.supportMaxDelegateLockPeriod()) { builder = DelegateResourceContract.newBuilder() - .setLock(true) - .setLockPeriod(chainBaseManager.getDynamicPropertiesStore().getMaxDelegateLockPeriod()) - .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + .setLock(true) + .setLockPeriod(dps.getMaxDelegateLockPeriod()) + .setBalance(balance); } else { builder = DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + .setLock(true) + .setBalance(balance); } - TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build() - , ContractType.DelegateResourceContract); - long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); - + long builderSize = builder.build().getSerializedSize(); DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() - .setBalance(TRX_PRECISION); - TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build() - , ContractType.DelegateResourceContract); - long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); - long addSize = Math.max(size1 - size2, 0L); + .setBalance(TRX_PRECISION); + long builder2Size = builder2.build().getSerializedSize(); + long addSize = Math.max(builderSize - builder2Size, 0L); return DELEGATE_COST_BASE_SIZE + addSize; } - } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java index 18eb543097b..b3772970248 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java @@ -3,6 +3,8 @@ import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; import com.google.common.primitives.Bytes; import com.google.protobuf.ByteString; @@ -49,7 +51,7 @@ public void validate(DelegateResourceParam param, Repository repo) throws Contra } long delegateBalance = param.getDelegateBalance(); if (delegateBalance < TRX_PRECISION) { - throw new ContractValidateException("delegateBalance must be more than 1TRX"); + throw new ContractValidateException("delegateBalance must be greater than or equal to 1 TRX"); } switch (param.getResourceType()) { @@ -60,16 +62,11 @@ public void validate(DelegateResourceParam param, Repository repo) throws Contra long netUsage = (long) (ownerCapsule.getNetUsage() * TRX_PRECISION * ((double) (repo.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); - long remainNetUsage = netUsage - - ownerCapsule.getFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage); - remainNetUsage = Math.max(0, remainNetUsage); - - if (ownerCapsule.getFrozenV2BalanceForBandwidth() - remainNetUsage < delegateBalance) { + if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) { throw new ContractValidateException( - "delegateBalance must be less than available FreezeBandwidthV2 balance"); + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance"); } } break; @@ -81,16 +78,11 @@ public void validate(DelegateResourceParam param, Repository repo) throws Contra long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) (repo.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); - long remainEnergyUsage = energyUsage - - ownerCapsule.getEnergyFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); - - remainEnergyUsage = Math.max(0, remainEnergyUsage); + long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage); - if (ownerCapsule.getFrozenV2BalanceForEnergy() - remainEnergyUsage < delegateBalance) { + if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) { throw new ContractValidateException( - "delegateBalance must be less than available FreezeEnergyV2 balance"); + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance"); } } break; diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java index c5c8fa91344..3088527ace6 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java @@ -30,9 +30,9 @@ public void validate(FreezeBalanceParam param, Repository repo) throws ContractV if (frozenBalance <= 0) { throw new ContractValidateException("FrozenBalance must be positive"); } else if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("FrozenBalance must be more than 1TRX"); + throw new ContractValidateException("FrozenBalance must be greater than or equal to 1 TRX"); } else if (frozenBalance > ownerCapsule.getBalance()) { - throw new ContractValidateException("FrozenBalance must be less than accountBalance"); + throw new ContractValidateException("FrozenBalance must be less than or equal to accountBalance"); } // validate frozen count of owner account diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java index b3dd258ae59..e7e932194ed 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java @@ -37,9 +37,10 @@ public void validate(FreezeBalanceV2Param param, Repository repo) throws Contrac if (frozenBalance <= 0) { throw new ContractValidateException("FrozenBalance must be positive"); } else if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("FrozenBalance must be more than 1TRX"); + throw new ContractValidateException("FrozenBalance must be greater than or equal to 1 TRX"); } else if (frozenBalance > ownerCapsule.getBalance()) { - throw new ContractValidateException("FrozenBalance must be less than accountBalance"); + throw new ContractValidateException( + "FrozenBalance must be less than or equal to accountBalance"); } // validate arg @resourceType diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java index d4cc2fcb8ce..d521e596e3e 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ArrayUtils; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.ChainBaseManager; @@ -49,7 +48,7 @@ public void validate(UnDelegateResourceParam param, Repository repo) throws Cont } byte[] receiverAddress = param.getReceiverAddress(); - if (ArrayUtils.isEmpty(receiverAddress) || !DecodeUtil.addressValid(receiverAddress)) { + if (!DecodeUtil.addressValid(receiverAddress)) { throw new ContractValidateException("Invalid receiverAddress"); } if (Arrays.equals(receiverAddress, ownerAddress)) { @@ -103,7 +102,9 @@ public void execute(UnDelegateResourceParam param, Repository repo) { case BANDWIDTH: BandwidthProcessor bandwidthProcessor = new BandwidthProcessor(ChainBaseManager.getInstance()); bandwidthProcessor.updateUsageForDelegated(receiverCapsule); - + /* For example, in a scenario where a regular account can be upgraded to a contract + account through an interface, the account information will be cleared after the + contract suicide, and this account will be converted to a regular account in the future */ if (receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth() < unDelegateBalance) { // A TVM contract suicide, re-create will produce this situation @@ -166,9 +167,8 @@ public void execute(UnDelegateResourceParam param, Repository repo) { BandwidthProcessor processor = new BandwidthProcessor(ChainBaseManager.getInstance()); if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { - ownerCapsule.setNetUsage(processor.unDelegateIncrease(ownerCapsule, receiverCapsule, - transferUsage, BANDWIDTH, now)); - ownerCapsule.setLatestConsumeTime(now); + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, + transferUsage, BANDWIDTH, now); } } break; @@ -181,9 +181,7 @@ public void execute(UnDelegateResourceParam param, Repository repo) { EnergyProcessor processor = new EnergyProcessor(dynamicStore, ChainBaseManager.getInstance().getAccountStore()); if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { - ownerCapsule.setEnergyUsage(processor.unDelegateIncrease(ownerCapsule, receiverCapsule, - transferUsage, ENERGY, now)); - ownerCapsule.setLatestConsumeTimeForEnergy(now); + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, transferUsage, ENERGY, now); } } break; diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java index da08a002677..0bcdb10d46f 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java @@ -60,8 +60,8 @@ private long getTotalWithdrawUnfreeze(List unfrozen } private List getTotalWithdrawList(List unfrozenV2List, long now) { - return unfrozenV2List.stream().filter(unfrozenV2 -> (unfrozenV2.getUnfreezeAmount() > 0 - && unfrozenV2.getUnfreezeExpireTime() <= now)).collect(Collectors.toList()); + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); } public long execute(WithdrawExpireUnfreezeParam param, Repository repo) throws ContractExeException { diff --git a/actuator/src/main/java/org/tron/core/vm/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index 90a59f53a36..e02ba225c6b 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Program.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Program.java @@ -9,6 +9,10 @@ import static org.apache.commons.lang3.ArrayUtils.nullToEmpty; import static org.tron.common.utils.ByteUtil.stripLeadingZeroes; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; +import static org.tron.protos.contract.Common.ResourceCode.UNRECOGNIZED; import com.google.protobuf.ByteString; import java.math.BigInteger; @@ -556,15 +560,8 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit bandwidthProcessor.updateUsageForDelegated(ownerCapsule); ownerCapsule.setLatestConsumeTime(now); if (ownerCapsule.getNetUsage() > 0) { - long newNetUsage = - bandwidthProcessor.unDelegateIncrease( - inheritorCapsule, - ownerCapsule, - ownerCapsule.getNetUsage(), - Common.ResourceCode.BANDWIDTH, - now); - inheritorCapsule.setNetUsage(newNetUsage); - inheritorCapsule.setLatestConsumeTime(now); + bandwidthProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, + ownerCapsule.getNetUsage(), BANDWIDTH, now); } EnergyProcessor energyProcessor = @@ -573,15 +570,8 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit energyProcessor.updateUsage(ownerCapsule); ownerCapsule.setLatestConsumeTimeForEnergy(now); if (ownerCapsule.getEnergyUsage() > 0) { - long newEnergyUsage = - energyProcessor.unDelegateIncrease( - inheritorCapsule, - ownerCapsule, - ownerCapsule.getEnergyUsage(), - Common.ResourceCode.ENERGY, - now); - inheritorCapsule.setEnergyUsage(newEnergyUsage); - inheritorCapsule.setLatestConsumeTimeForEnergy(now); + energyProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, + ownerCapsule.getEnergyUsage(), ENERGY, now); } // withdraw expire unfrozen balance @@ -608,9 +598,9 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit private void clearOwnerFreezeV2(AccountCapsule ownerCapsule) { ownerCapsule.clearFrozenV2(); ownerCapsule.setNetUsage(0); - ownerCapsule.setNewWindowSize(Common.ResourceCode.BANDWIDTH, 0); + ownerCapsule.setNewWindowSize(BANDWIDTH, 0); ownerCapsule.setEnergyUsage(0); - ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 0); + ownerCapsule.setNewWindowSize(ENERGY, 0); ownerCapsule.clearUnfrozenV2(); } @@ -2091,11 +2081,11 @@ public boolean unDelegateResource( private Common.ResourceCode parseResourceCode(DataWord resourceType) { switch (resourceType.intValue()) { case 0: - return Common.ResourceCode.BANDWIDTH; + return BANDWIDTH; case 1: - return Common.ResourceCode.ENERGY; + return ENERGY; default: - return Common.ResourceCode.UNRECOGNIZED; + return UNRECOGNIZED; } } @@ -2104,13 +2094,13 @@ private Common.ResourceCode parseResourceCodeV2(DataWord resourceType) { byte type = resourceType.sValue().byteValueExact(); switch (type) { case 0: - return Common.ResourceCode.BANDWIDTH; + return BANDWIDTH; case 1: - return Common.ResourceCode.ENERGY; + return ENERGY; case 2: - return Common.ResourceCode.TRON_POWER; + return TRON_POWER; default: - return Common.ResourceCode.UNRECOGNIZED; + return UNRECOGNIZED; } } catch (ArithmeticException e) { logger.warn("TVM ParseResourceCodeV2: invalid resource code: {}", resourceType.sValue()); diff --git a/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java index 9a22f796228..7bc760f9edf 100644 --- a/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java +++ b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java @@ -12,8 +12,6 @@ import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; -import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; - public class FreezeV2Util { private FreezeV2Util() { @@ -163,13 +161,8 @@ public static long queryDelegatableResource(byte[] address, long type, Repositor return frozenV2Resource; } - long remainNetUsage = usage - - accountCapsule.getFrozenBalance() - - accountCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() - - accountCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); - - remainNetUsage = Math.max(0, remainNetUsage); - return Math.max(0L, frozenV2Resource - remainNetUsage); + long v2NetUsage = getV2NetUsage(accountCapsule, usage); + return Math.max(0L, frozenV2Resource - v2NetUsage); } if (type == 1) { @@ -188,13 +181,8 @@ public static long queryDelegatableResource(byte[] address, long type, Repositor return frozenV2Resource; } - long remainEnergyUsage = usage - - accountCapsule.getEnergyFrozenBalance() - - accountCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() - - accountCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); - - remainEnergyUsage = Math.max(0, remainEnergyUsage); - return Math.max(0L, frozenV2Resource - remainEnergyUsage); + long v2EnergyUsage = getV2EnergyUsage(accountCapsule, usage); + return Math.max(0L, frozenV2Resource - v2EnergyUsage); } return 0L; @@ -246,8 +234,24 @@ private static long getTotalWithdrawUnfreeze(List u } private static List getTotalWithdrawList(List unfrozenV2List, long now) { - return unfrozenV2List.stream().filter(unfrozenV2 -> (unfrozenV2.getUnfreezeAmount() > 0 - && unfrozenV2.getUnfreezeExpireTime() <= now)).collect(Collectors.toList()); + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); + } + + public static long getV2NetUsage(AccountCapsule ownerCapsule, long netUsage) { + long v2NetUsage= netUsage + - ownerCapsule.getFrozenBalance() + - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() + - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + return Math.max(0, v2NetUsage); + } + + public static long getV2EnergyUsage(AccountCapsule ownerCapsule, long energyUsage) { + long v2EnergyUsage= energyUsage + - ownerCapsule.getEnergyFrozenBalance() + - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() + - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); + return Math.max(0, v2EnergyUsage); } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java index 13f3cf576f1..b60fed63cda 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -1452,4 +1452,20 @@ public void setNewWindowSizeV2( ResourceCode resourceCode, long newWindowSize) { } } + public void setUsage(ResourceCode resourceCode, long usage) { + if (resourceCode == BANDWIDTH) { + setNetUsage(usage); + } else { + setEnergyUsage(usage); + } + } + + public void setLatestTime(ResourceCode resourceCode, long time) { + if (resourceCode == BANDWIDTH) { + setLatestConsumeTime(time); + } else { + setLatestConsumeTimeForEnergy(time); + } + } + } diff --git a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java index 87472b6212f..a7a22390958 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -1,7 +1,5 @@ package org.tron.core.db; -import static java.lang.Math.ceil; -import static java.lang.Math.round; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; @@ -127,16 +125,17 @@ public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, long remainWindowSize = oldWindowSizeV2 - (now - lastTime) * WINDOW_SIZE_PRECISION; long newWindowSize = divideCeil( - remainUsage * remainWindowSize + usage * this.windowSize * WINDOW_SIZE_PRECISION, newUsage); + remainUsage * remainWindowSize + usage * this.windowSize * WINDOW_SIZE_PRECISION, newUsage); newWindowSize = Math.min(newWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); accountCapsule.setNewWindowSizeV2(resourceCode, newWindowSize); return newUsage; } - public long unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiver, + public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiver, long transferUsage, ResourceCode resourceCode, long now) { if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { - return unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now); + unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now); + return; } long lastOwnerTime = owner.getLastConsumeTime(resourceCode); long ownerUsage = owner.getUsage(resourceCode); @@ -152,16 +151,19 @@ public long unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv // mean ownerUsage == 0 and transferUsage == 0 if (newOwnerUsage == 0) { owner.setNewWindowSize(resourceCode, this.windowSize); - return newOwnerUsage; + owner.setUsage(resourceCode, 0); + owner.setLatestTime(resourceCode, now); + return; } // calculate new windowSize long newOwnerWindowSize = getNewWindowSize(ownerUsage, remainOwnerWindowSize, transferUsage, remainReceiverWindowSize, newOwnerUsage); owner.setNewWindowSize(resourceCode, newOwnerWindowSize); - return newOwnerUsage; + owner.setUsage(resourceCode, newOwnerUsage); + owner.setLatestTime(resourceCode, now); } - public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver, + public void unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver, long transferUsage, ResourceCode resourceCode, long now) { long lastOwnerTime = owner.getLastConsumeTime(resourceCode); long ownerUsage = owner.getUsage(resourceCode); @@ -171,7 +173,9 @@ public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule rece // mean ownerUsage == 0 and transferUsage == 0 if (newOwnerUsage == 0) { owner.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION); - return newOwnerUsage; + owner.setUsage(resourceCode, 0); + owner.setLatestTime(resourceCode, now); + return; } long remainOwnerWindowSizeV2 = owner.getWindowSizeV2(resourceCode); @@ -186,7 +190,8 @@ public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule rece newOwnerUsage); newOwnerWindowSize = Math.min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); owner.setNewWindowSizeV2(resourceCode, newOwnerWindowSize); - return newOwnerUsage; + owner.setUsage(resourceCode, newOwnerUsage); + owner.setLatestTime(resourceCode, now); } private long getNewWindowSize(long lastUsage, long lastWindowSize, long usage, diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 5f8c9ff89fc..f3059d31558 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -1,5 +1,6 @@ package org.tron.core.store; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; import com.google.protobuf.ByteString; @@ -2824,11 +2825,12 @@ public long getMaxDelegateLockPeriod() { return Optional.ofNullable(getUnchecked(MAX_DELEGATE_LOCK_PERIOD)) .map(BytesCapsule::getData) .map(ByteArray::toLong) - .orElse(DELEGATE_PERIOD / 3000); + .orElse(DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL); } public boolean supportMaxDelegateLockPeriod() { - return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / 3000) && getUnfreezeDelayDays() > 0; + return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL) && + getUnfreezeDelayDays() > 0; } private static class DynamicResourceProperties { diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index 6bbc66846bd..b1a948e9fdf 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -77,6 +77,7 @@ public class ChainConstant { public static final long TRX_PRECISION = 1000_000L; public static final long DELEGATE_COST_BASE_SIZE = 275L; public static final long WINDOW_SIZE_PRECISION = 1000L; + public static final long ONE_YEAR_BLOCK_NUMBERS = 10512000L; } public class NodeConstant { diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 3560a7032bc..1ddc57fdc8c 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -21,6 +21,7 @@ import static org.tron.common.utils.Commons.getAssetIssueStoreFinal; import static org.tron.common.utils.Commons.getExchangeStoreFinal; import static org.tron.common.utils.WalletUtil.isConstant; +import static org.tron.core.capsule.utils.TransactionUtil.buildInternalTransaction; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.core.config.Parameter.DatabaseConstants.EXCHANGE_COUNT_LIMIT_MAX; @@ -28,6 +29,8 @@ import static org.tron.core.config.Parameter.DatabaseConstants.PROPOSAL_COUNT_LIMIT_MAX; import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.parseEnergyFee; import static org.tron.core.services.jsonrpc.TronJsonRpcImpl.EARLIEST_STR; +import static org.tron.core.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; import static org.tron.protos.contract.Common.ResourceCode; import com.google.common.collect.ContiguousSet; @@ -152,7 +155,6 @@ import org.tron.core.capsule.TransactionRetCapsule; import org.tron.core.capsule.WitnessCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.capsule.utils.TransactionUtil; import org.tron.core.config.args.Args; import org.tron.core.db.BandwidthProcessor; import org.tron.core.db.BlockIndexStore; @@ -191,6 +193,7 @@ import org.tron.core.store.MarketPairPriceToOrderStore; import org.tron.core.store.MarketPairToPriceStore; import org.tron.core.store.StoreFactory; +import org.tron.core.utils.TransactionUtil; import org.tron.core.vm.program.Program; import org.tron.core.zen.ShieldedTRC20ParametersBuilder; import org.tron.core.zen.ShieldedTRC20ParametersBuilder.ShieldedTRC20ParametersType; @@ -782,6 +785,10 @@ public GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage getCanWithdrawUnfreezeAm ByteString ownerAddress, long timestamp) { GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage.Builder builder = GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage.newBuilder(); + if (timestamp < 0) { + return builder.build(); + } + long canWithdrawUnfreezeAmount; AccountStore accountStore = chainBaseManager.getAccountStore(); @@ -799,13 +806,8 @@ public GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage getCanWithdrawUnfreezeAm long finalTimestamp = timestamp; canWithdrawUnfreezeAmount = unfrozenV2List - .stream() - .filter(unfrozenV2 -> - (unfrozenV2.getUnfreezeAmount() > 0 - && unfrozenV2.getUnfreezeExpireTime() <= finalTimestamp)) - .mapToLong(UnFreezeV2::getUnfreezeAmount) - .sum(); - + .stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= finalTimestamp) + .mapToLong(UnFreezeV2::getUnfreezeAmount).sum(); builder.setAmount(canWithdrawUnfreezeAmount); return builder.build(); @@ -844,13 +846,7 @@ public GrpcAPI.GetAvailableUnfreezeCountResponseMessage getAvailableUnfreezeCoun } long now = dynamicStore.getLatestBlockHeaderTimestamp(); - List unfrozenV2List = accountCapsule.getInstance().getUnfrozenV2List(); - long getUsedUnfreezeCount = unfrozenV2List - .stream() - .filter(unfrozenV2 -> - (unfrozenV2.getUnfreezeAmount() > 0 - && unfrozenV2.getUnfreezeExpireTime() > now)) - .count(); + long getUsedUnfreezeCount = accountCapsule.getUnfreezingV2Count(now); getAvailableUnfreezeCount = UnfreezeBalanceV2Actuator.getUNFREEZE_MAX_TIMES() - getUsedUnfreezeCount; builder.setCount(getAvailableUnfreezeCount); @@ -870,20 +866,15 @@ public long calcCanDelegatedBandWidthMaxSize( processor.updateUsage(ownerCapsule); long accountNetUsage = ownerCapsule.getNetUsage(); - accountNetUsage += org.tron.core.utils.TransactionUtil.estimateConsumeBandWidthSize( - ownerCapsule, chainBaseManager); + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore, + ownerCapsule.getBalance()); long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); - long remainNetUsage = netUsage - - ownerCapsule.getFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage); - remainNetUsage = Math.max(0, remainNetUsage); - - long maxSize = ownerCapsule.getFrozenV2BalanceForBandwidth() - remainNetUsage; + long maxSize = ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage; return Math.max(0, maxSize); } @@ -901,14 +892,9 @@ public long calcCanDelegatedEnergyMaxSize(ByteString ownerAddress) { long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) (dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); - long remainEnergyUsage = energyUsage - - ownerCapsule.getEnergyFrozenBalance() - - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() - - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); - - remainEnergyUsage = Math.max(0, remainEnergyUsage); + long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage); - long maxSize = ownerCapsule.getFrozenV2BalanceForEnergy() - remainEnergyUsage; + long maxSize = ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage; return Math.max(0, maxSize); } @@ -3058,7 +3044,7 @@ public Transaction callConstantContract(TransactionCapsule trxCap, result.getLogInfoList().forEach(logInfo -> builder.addLogs(LogInfo.buildLog(logInfo))); result.getInternalTransactions().forEach(it -> - builder.addInternalTransactions(TransactionUtil.buildInternalTransaction(it))); + builder.addInternalTransactions(buildInternalTransaction(it))); ret.setStatus(0, code.SUCESS); if (StringUtils.isNoneEmpty(result.getRuntimeError())) { ret.setStatus(0, code.FAILED); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java index 78096564e48..59df7021249 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java @@ -842,20 +842,20 @@ private TVMTestResult unDelegateResource( acquiredBalance = res == 0 ? oldReceiver.getAcquiredDelegatedFrozenV2BalanceForBandwidth() : oldReceiver.getAcquiredDelegatedFrozenV2BalanceForEnergy(); + long unDelegateMaxUsage; if (res == 0) { - long unDelegateMaxUsage = (long) (amount / TRX_PRECISION + unDelegateMaxUsage = (long) (amount / TRX_PRECISION * ((double) (dynamicStore.getTotalNetLimit()) / dynamicStore.getTotalNetWeight())); transferUsage = (long) (oldReceiver.getNetUsage() * ((double) (amount) / oldReceiver.getAllFrozenBalanceForBandwidth())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); } else { - long unDelegateMaxUsage = (long) (amount / TRX_PRECISION + unDelegateMaxUsage = (long) (amount / TRX_PRECISION * ((double) (dynamicStore.getTotalEnergyCurrentLimit()) / dynamicStore.getTotalEnergyWeight())); transferUsage = (long) (oldReceiver.getEnergyUsage() * ((double) (amount) / oldReceiver.getAllFrozenBalanceForEnergy())); - transferUsage = Math.min(unDelegateMaxUsage, transferUsage); } + transferUsage = Math.min(unDelegateMaxUsage, transferUsage); } DelegatedResourceStore delegatedResourceStore = manager.getDelegatedResourceStore(); @@ -1002,28 +1002,18 @@ private TVMTestResult suicide(byte[] callerAddr, byte[] contractAddr, byte[] inh newInheritor.getFrozenBalance() - oldInheritorFrozenBalance); if (oldInheritor != null) { if (oldContract.getNetUsage() > 0) { - long expectedNewNetUsage = - bandwidthProcessor.unDelegateIncrease( - oldInheritor, - oldContract, - oldContract.getNetUsage(), - Common.ResourceCode.BANDWIDTH, - now); + bandwidthProcessor.unDelegateIncrease(oldInheritor, oldContract, oldContract.getNetUsage(), + Common.ResourceCode.BANDWIDTH, now); Assert.assertEquals( - expectedNewNetUsage, newInheritor.getNetUsage() - oldInheritorBandwidthUsage); + oldInheritor.getNetUsage(), newInheritor.getNetUsage() - oldInheritorBandwidthUsage); Assert.assertEquals( ChainBaseManager.getInstance().getHeadSlot(), newInheritor.getLatestConsumeTime()); } if (oldContract.getEnergyUsage() > 0) { - long expectedNewEnergyUsage = - energyProcessor.unDelegateIncrease( - oldInheritor, - oldContract, - oldContract.getEnergyUsage(), - Common.ResourceCode.ENERGY, - now); + energyProcessor.unDelegateIncrease(oldInheritor, oldContract, + oldContract.getEnergyUsage(), Common.ResourceCode.ENERGY, now); Assert.assertEquals( - expectedNewEnergyUsage, newInheritor.getEnergyUsage() - oldInheritorEnergyUsage); + oldInheritor.getEnergyUsage(), newInheritor.getEnergyUsage() - oldInheritorEnergyUsage); Assert.assertEquals( ChainBaseManager.getInstance().getHeadSlot(), newInheritor.getLatestConsumeTimeForEnergy()); diff --git a/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java index b20d55fd983..f49f39baabd 100644 --- a/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java @@ -1,6 +1,9 @@ package org.tron.core.actuator; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +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.junit.Assert.fail; @@ -13,7 +16,6 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.tron.common.BaseTest; @@ -179,7 +181,8 @@ public void testDelegateResourceWithNoFreeze() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { fail(); @@ -193,7 +196,7 @@ public void testDelegateResourceWithNoFreeze() { fail("cannot run here."); } catch (ContractValidateException e) { assertEquals( - "delegateBalance must be less than available FreezeEnergyV2 balance", + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); @@ -222,7 +225,8 @@ public void testDelegateBandwidthWithUsage() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); @@ -252,7 +256,7 @@ public void testDelegateCpuWithUsage() { fail("cannot run here."); } catch (ContractValidateException e) { assertEquals( - "delegateBalance must be less than available FreezeEnergyV2 balance", + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); @@ -407,9 +411,9 @@ public void testLockedDelegateResourceForBandwidth() { .get(DelegatedResourceCapsule .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), ByteArray.fromHexString(RECEIVER_ADDRESS), true)); - Assert.assertNull(delegatedResourceCapsule); - Assert.assertNotNull(lockedResourceCapsule); - Assert.assertNotEquals(0, lockedResourceCapsule.getExpireTimeForBandwidth()); + assertNull(delegatedResourceCapsule); + assertNotNull(lockedResourceCapsule); + assertNotEquals(0, lockedResourceCapsule.getExpireTimeForBandwidth()); assertEquals(delegateBalance, lockedResourceCapsule.getFrozenBalanceForBandwidth()); long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); assertEquals(totalNetWeightBefore, totalNetWeightAfter); @@ -662,7 +666,8 @@ public void delegateLessThanZero() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - assertEquals("delegateBalance must be more than 1TRX", e.getMessage()); + assertEquals("delegateBalance must be greater than or equal to 1 TRX", + e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); } @@ -700,7 +705,8 @@ public void delegateMoreThanBalance() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java index abcaf538e93..c66a86fe58c 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java @@ -137,7 +137,7 @@ public void testFreezeBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -145,10 +145,8 @@ public void testFreezeBalanceForBandwidth() { - TRANSFER_FEE); Assert.assertEquals(owner.getFrozenBalance(), frozenBalance); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -164,7 +162,7 @@ public void testFreezeBalanceForEnergy() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -173,10 +171,8 @@ public void testFreezeBalanceForEnergy() { Assert.assertEquals(0L, owner.getFrozenBalance()); Assert.assertEquals(frozenBalance, owner.getEnergyFrozenBalance()); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -206,9 +202,9 @@ public void testFreezeDelegatedBalanceForBandwidthWithContractAddress() { actuator.validate(); actuator.execute(ret); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), "Do not allow delegate resources to contract addresses"); + Assert.assertEquals("Do not allow delegate resources to contract addresses", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -227,7 +223,7 @@ public void testFreezeDelegatedBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -258,9 +254,8 @@ public void testFreezeDelegatedBalanceForBandwidth() { Assert .assertEquals(0, delegatedResourceAccountIndexCapsuleOwner.getFromAccountsList().size()); Assert.assertEquals(1, delegatedResourceAccountIndexCapsuleOwner.getToAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsuleReceiver = dbManager .getDelegatedResourceAccountIndexStore().get(ByteArray.fromHexString(RECEIVER_ADDRESS)); @@ -269,15 +264,12 @@ public void testFreezeDelegatedBalanceForBandwidth() { Assert .assertEquals(1, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -359,7 +351,7 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -394,9 +386,8 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { Assert .assertEquals(0, delegatedResourceAccountIndexCapsuleOwner.getFromAccountsList().size()); Assert.assertEquals(1, delegatedResourceAccountIndexCapsuleOwner.getToAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsuleReceiver = dbManager .getDelegatedResourceAccountIndexStore().get(ByteArray.fromHexString(RECEIVER_ADDRESS)); @@ -405,14 +396,11 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { Assert .assertEquals(1, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -430,7 +418,7 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenClose() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance - frozenBalance @@ -450,10 +438,8 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenClose() { Assert.assertEquals(totalEnergyWeightBefore + frozenBalance / 1000_000L, totalEnergyWeightAfter); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -471,10 +457,9 @@ public void freezeLessThanZero() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenBalance must be positive", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -492,10 +477,10 @@ public void freezeMoreThanBalance() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be less than accountBalance", e.getMessage()); + Assert.assertEquals( + "frozenBalance must be less than or equal to accountBalance", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -514,12 +499,9 @@ public void invalidOwnerAddress() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Invalid address", e.getMessage()); - } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -538,11 +520,10 @@ public void invalidOwnerAccount() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -563,11 +544,10 @@ public void durationLessThanMin() { } catch (ContractValidateException e) { long minFrozenTime = dbManager.getDynamicPropertiesStore().getMinFrozenTime(); long maxFrozenTime = dbManager.getDynamicPropertiesStore().getMaxFrozenTime(); - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenDuration must be less than " + maxFrozenTime + " days " + "and more than " + minFrozenTime + " days", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -587,11 +567,10 @@ public void durationMoreThanMax() { } catch (ContractValidateException e) { long minFrozenTime = dbManager.getDynamicPropertiesStore().getMinFrozenTime(); long maxFrozenTime = dbManager.getDynamicPropertiesStore().getMaxFrozenTime(); - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenDuration must be less than " + maxFrozenTime + " days " + "and more than " + minFrozenTime + " days", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -609,10 +588,10 @@ public void lessThan1TrxTest() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be more than 1TRX", e.getMessage()); + Assert.assertEquals("frozenBalance must be greater than or equal to 1 TRX", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -636,10 +615,9 @@ public void frozenNumTest() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenCount must be 0 or 1", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -655,10 +633,8 @@ public void moreThanFrozenNumber() { try { actuator.validate(); actuator.execute(ret); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } try { actuator.validate(); @@ -666,11 +642,10 @@ public void moreThanFrozenNumber() { fail("cannot run here."); } catch (ContractValidateException e) { long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -711,16 +686,14 @@ public void testFreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(-1L, owner.getInstance().getOldTronPower()); Assert.assertEquals(0L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -744,16 +717,14 @@ public void testFreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(100L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -777,18 +748,15 @@ public void testFreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(frozenBalance + 100L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } - } diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java index 082338df753..1e6039c3e69 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java @@ -129,7 +129,7 @@ public void testFreezeBalanceForBandwidth() { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -137,10 +137,8 @@ public void testFreezeBalanceForBandwidth() { - TRANSFER_FEE); Assert.assertEquals(owner.getFrozenV2BalanceForBandwidth(), frozenBalance); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -155,7 +153,7 @@ public void testFreezeBalanceForEnergy() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -164,10 +162,8 @@ public void testFreezeBalanceForEnergy() { Assert.assertEquals(0L, owner.getAllFrozenBalanceForBandwidth()); Assert.assertEquals(frozenBalance, owner.getAllFrozenBalanceForEnergy()); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -185,10 +181,9 @@ public void freezeLessThanZero() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenBalance must be positive", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -205,10 +200,10 @@ public void freezeMoreThanBalance() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be less than accountBalance", e.getMessage()); + Assert.assertEquals("frozenBalance must be less than or equal to accountBalance", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -226,12 +221,9 @@ public void invalidOwnerAddress() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Invalid address", e.getMessage()); - } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -249,11 +241,10 @@ public void invalidOwnerAccount() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -270,10 +261,10 @@ public void lessThan1TrxTest() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be more than 1TRX", e.getMessage()); + Assert.assertEquals("frozenBalance must be greater than or equal to 1 TRX", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -288,10 +279,8 @@ public void moreThanFrozenNumber() { try { actuator.validate(); actuator.execute(ret); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } try { actuator.validate(); @@ -299,11 +288,9 @@ public void moreThanFrozenNumber() { fail("cannot run here."); } catch (ContractValidateException e) { long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -343,16 +330,14 @@ public void testFreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(-1L, owner.getInstance().getOldTronPower()); Assert.assertEquals(0L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -360,7 +345,6 @@ public void testFreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() @Test public void testFreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { long frozenBalance = 1_000_000_000L; - long duration = 3; FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); @@ -377,16 +361,14 @@ public void testFreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(100L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -409,19 +391,16 @@ public void testFreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(100L, owner.getTronPower()); Assert.assertEquals(frozenBalance + 100, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } - } diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java index 3f9b999228c..77e70f6762e 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java @@ -110,8 +110,8 @@ public void testUnfreezeBalanceForBandwidth() { AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozen(frozenBalance, now); - Assert.assertEquals(accountCapsule.getFrozenBalance(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenBalance()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -124,22 +124,20 @@ public void testUnfreezeBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); - Assert.assertEquals(owner.getFrozenBalance(), 0); - Assert.assertEquals(owner.getTronPower(), 0L); + Assert.assertEquals(0, owner.getFrozenBalance()); + Assert.assertEquals(0L, owner.getTronPower()); long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); Assert.assertEquals(totalNetWeightBefore, totalNetWeightAfter + frozenBalance / 1000_000L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -204,12 +202,12 @@ public void testUnfreezeSelfAndOthersForBandwidth() { actuator1.execute(ret1); long afterWeight1 = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); Assert.assertEquals(1, afterWeight1); - Assert.assertEquals(ret1.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret1.getInstance().getRet()); } catch (ContractValidateException e) { logger.error("ContractValidateException", e); - Assert.assertFalse(e instanceof ContractValidateException); + Assert.fail(); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -222,11 +220,9 @@ public void testUnfreezeSelfAndOthersForBandwidth() { actuator.execute(ret); long afterWeight = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); Assert.assertEquals(0, afterWeight); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowNewReward(0); } @@ -240,8 +236,8 @@ public void testUnfreezeBalanceForEnergy() { AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozenForEnergy(frozenBalance, now); - Assert.assertEquals(accountCapsule.getAllFrozenBalanceForEnergy(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getAllFrozenBalanceForEnergy()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -253,20 +249,18 @@ public void testUnfreezeBalanceForEnergy() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); - Assert.assertEquals(owner.getEnergyFrozenBalance(), 0); - Assert.assertEquals(owner.getTronPower(), 0L); + Assert.assertEquals(0, owner.getEnergyFrozenBalance()); + Assert.assertEquals(0L, owner.getTronPower()); long totalEnergyWeightAfter = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); Assert.assertEquals(totalEnergyWeightBefore, totalEnergyWeightAfter + frozenBalance / 1000_000L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -325,7 +319,7 @@ public void testUnfreezeDelegatedBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -352,10 +346,8 @@ public void testUnfreezeDelegatedBalanceForBandwidth() { Assert.assertEquals(0, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -419,17 +411,18 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithDeletedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist"); + Assert.assertEquals( + "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -453,11 +446,8 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithDeletedReceiver() { Assert.assertEquals(0, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - } catch (ContractValidateException e) { - logger.error("", e); - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -532,10 +522,11 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithRecreatedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "AcquiredDelegatedFrozenBalanceForBandwidth[10] < delegatedBandwidth[1000000000]"); + Assert.assertEquals( + "AcquiredDelegatedFrozenBalanceForBandwidth[10] < delegatedBandwidth[1000000000]", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); @@ -543,7 +534,7 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithRecreatedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -638,10 +629,9 @@ public void testUnfreezeDelegatedBalanceForBandwidthSameTokenNameClose() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("no frozenBalance(BANDWIDTH)", e.getMessage()); } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -678,7 +668,7 @@ public void testUnfreezeDelegatedBalanceForCpu() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -689,11 +679,8 @@ public void testUnfreezeDelegatedBalanceForCpu() { Assert.assertEquals(0L, ownerResult.getTronPower()); Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); Assert.assertEquals(0L, receiverResult.getAllFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - logger.error("", e); - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -734,10 +721,11 @@ public void testUnfreezeDelegatedBalanceForCpuWithDeletedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist"); + Assert.assertEquals( + "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); @@ -745,17 +733,15 @@ public void testUnfreezeDelegatedBalanceForCpuWithDeletedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(initBalance + frozenBalance, ownerResult.getBalance()); Assert.assertEquals(0L, ownerResult.getTronPower()); Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -809,10 +795,11 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "AcquiredDelegatedFrozenBalanceForEnergy[10] < delegatedEnergy[1000000000]"); + Assert.assertEquals( + "AcquiredDelegatedFrozenBalanceForEnergy[10] < delegatedEnergy[1000000000]", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); @@ -821,7 +808,7 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -830,9 +817,7 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); receiver = dbManager.getAccountStore().get(receiver.createDbKey()); Assert.assertEquals(0, receiver.getAcquiredDelegatedFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - Assert.fail(); - } catch (ContractExeException e) { + } catch (ContractValidateException | ContractExeException e) { Assert.fail(); } } @@ -856,12 +841,9 @@ public void invalidOwnerAddress() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Invalid address", e.getMessage()); - } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -884,11 +866,10 @@ public void invalidOwnerAccount() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -904,10 +885,9 @@ public void noFrozenBalance() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("no frozenBalance(BANDWIDTH)", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -930,17 +910,15 @@ public void notTimeToUnfreeze() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("It's not time to unfreeze(BANDWIDTH).", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @Test public void testClearVotes() { byte[] ownerAddressBytes = ByteArray.fromHexString(OWNER_ADDRESS); - ByteString ownerAddress = ByteString.copyFrom(ownerAddressBytes); long now = System.currentTimeMillis(); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); @@ -960,14 +938,12 @@ public void testClearVotes() { VotesCapsule votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); Assert.assertNotNull(votesCapsule); Assert.assertEquals(0, votesCapsule.getNewVotes().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } // if had votes - List oldVotes = new ArrayList(); + List oldVotes = new ArrayList<>(); VotesCapsule votesCapsule = new VotesCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), oldVotes); votesCapsule.addNewVotes(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -981,10 +957,8 @@ public void testClearVotes() { votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); Assert.assertNotNull(votesCapsule); Assert.assertEquals(0, votesCapsule.getNewVotes().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1063,8 +1037,8 @@ public void commonErrorCheck() { AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozen(frozenBalance, now); - Assert.assertEquals(accountCapsule.getFrozenBalance(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenBalance()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1087,7 +1061,7 @@ public void testUnfreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() accountCapsule.setFrozenForEnergy(frozenBalance, now); accountCapsule.setOldTronPower(frozenBalance); accountCapsule.addVotes(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); - Assert.assertEquals(accountCapsule.getAllFrozenBalanceForEnergy(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getAllFrozenBalanceForEnergy()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -1098,16 +1072,14 @@ public void testUnfreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(0L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1133,16 +1105,14 @@ public void testUnfreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 1L); + Assert.assertEquals(1L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1168,16 +1138,14 @@ public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(0L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1198,13 +1166,12 @@ public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContractForTronPower(OWNER_ADDRESS)); - TransactionResultCapsule ret = new TransactionResultCapsule(); try { actuator.validate(); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("It's not time to unfreeze(TronPower).", e.getMessage()); } } diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java index 14a6de98606..db2a78b1623 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java @@ -629,8 +629,7 @@ public void testUnfreezeBalanceCalcUnfreezeExpireTime() { .build(); long ret = actuator.calcUnfreezeExpireTime(now); - - Assert.assertTrue(true); + Assert.assertTrue(ret > 0); } @Test diff --git a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java index 0baaad7c962..7d737870e58 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java @@ -4,7 +4,9 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.core.utils.TransactionUtil.validAccountId; import static org.tron.core.utils.TransactionUtil.validAccountName; import static org.tron.core.utils.TransactionUtil.validAssetName; @@ -12,19 +14,27 @@ import com.google.protobuf.ByteString; import java.nio.charset.StandardCharsets; +import java.util.List; import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; +import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionCapsule; import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.utils.TransactionUtil; +import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; - +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; @Slf4j(topic = "capsule") public class TransactionUtilTest extends BaseTest { @@ -39,7 +49,6 @@ public static void init() { dbPath = "output_transactionUtil_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - } @Before @@ -55,6 +64,82 @@ public void setUp() { dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); } + // only for testing + public static long consumeBandWidthSize( + final TransactionCapsule transactionCapsule, + ChainBaseManager chainBaseManager) { + long bs; + + boolean supportVM = chainBaseManager.getDynamicPropertiesStore().supportVM(); + if (supportVM) { + bs = transactionCapsule.getInstance().toBuilder().clearRet().build().getSerializedSize(); + } else { + bs = transactionCapsule.getSerializedSize(); + } + + List contracts = transactionCapsule.getInstance().getRawData() + .getContractList(); + for (Transaction.Contract contract : contracts) { + if (contract.getType() == Transaction.Contract.ContractType.ShieldedTransferContract) { + continue; + } + if (supportVM) { + bs += Constant.MAX_RESULT_SIZE_IN_TX; + } + } + + return bs; + } + + // only for testing + public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsule, + ChainBaseManager chainBaseManager) { + DelegateResourceContract.Builder builder; + if (chainBaseManager.getDynamicPropertiesStore().supportMaxDelegateLockPeriod()) { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setLockPeriod(chainBaseManager.getDynamicPropertiesStore().getMaxDelegateLockPeriod()) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + } else { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + } + TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build(), + ContractType.DelegateResourceContract); + long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); + + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), + ContractType.DelegateResourceContract); + long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); + long addSize = Math.max(size1 - size2, 0L); + + return DELEGATE_COST_BASE_SIZE + addSize; + } + + // only for testing + public static long estimateConsumeBandWidthSizeOld( + final AccountCapsule ownerCapsule, + ChainBaseManager chainBaseManager) { + DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build(), + ContractType.DelegateResourceContract); + long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); + + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), + ContractType.DelegateResourceContract); + long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); + long addSize = Math.max(size1 - size2, 0L); + + return DELEGATE_COST_BASE_SIZE + addSize; + } + @Test public void validAccountNameCheck() { StringBuilder account = new StringBuilder(); @@ -65,7 +150,6 @@ public void validAccountNameCheck() { assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); account.append('z'); assertFalse(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); - } @Test @@ -147,7 +231,7 @@ public void isNumberCheck() { public void testEstimateConsumeBandWidthSize() { AccountCapsule ownerCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - long estimateConsumeBandWidthSize = TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, + long estimateConsumeBandWidthSize = estimateConsumeBandWidthSize(ownerCapsule, dbManager.getChainBaseManager()); assertEquals(275L, estimateConsumeBandWidthSize); chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); @@ -159,10 +243,193 @@ public void testEstimateConsumeBandWidthSize2() { chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); AccountCapsule ownerCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - long estimateConsumeBandWidthSize = TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, + long estimateConsumeBandWidthSize = estimateConsumeBandWidthSize(ownerCapsule, dbManager.getChainBaseManager()); assertEquals(277L, estimateConsumeBandWidthSize); chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); } + + @Test + public void testEstimateConsumeBandWidthSizeOld() { + dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + long balance = 1000_000L; + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + ownerCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize1 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(277, estimateConsumeBandWidthSize1); + + balance = 1000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize2 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(279, estimateConsumeBandWidthSize2); + + balance = 1000_000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize3 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(280, estimateConsumeBandWidthSize3); + + balance = 1000_000_000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize4 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); + } + + + @Test + public void testEstimateConsumeBandWidthSizeNew() { + long balance = 1000_000L; + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(277, estimateConsumeBandWidthSize1); + + balance = 1000_000_000L; + long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(279, estimateConsumeBandWidthSize2); + + balance = 1000_000_000_000L; + long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(280, estimateConsumeBandWidthSize3); + + balance = 1000_000_000_000_000L; + long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); + } + + + @Test + public void testEstimateConsumeBandWidthSize3() { + dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = 1000_000L; + + AccountCapsule ownerCapsule; + long estimateConsumeBandWidthSizeOld; + long estimateConsumeBandWidthSizeNew; + + for (int i = 0; i < 100; i++) { + // old value is + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + estimateConsumeBandWidthSizeOld = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + + // new value is + estimateConsumeBandWidthSizeNew = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + + System.out.println("balance:" + + balance + + ", estimateConsumeBandWidthSizeOld:" + + estimateConsumeBandWidthSizeOld + + ", estimateConsumeBandWidthSizeNew:" + + estimateConsumeBandWidthSizeNew); + // new value assert equal to old value + Assert.assertEquals(estimateConsumeBandWidthSizeOld, estimateConsumeBandWidthSizeNew); + + // balance accumulated + balance = balance * 10; + if (balance < 0) { + break; + } + } + + } + + @Test + public void estimateConsumeBandWidthSizePositive() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = 100; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeBoundary() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = TRX_PRECISION; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeEdge() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = TRX_PRECISION + 1; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeCorner() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = Long.MAX_VALUE; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } }