From ebd21421438a8c02ca00d51368858249451d588c Mon Sep 17 00:00:00 2001 From: liuxincheng Date: Thu, 13 Apr 2023 15:20:42 +0800 Subject: [PATCH 1/3] fix(freezeV2): optimize Stake2.0 code --- .../actuator/DelegateResourceActuator.java | 28 +-- .../core/actuator/FreezeBalanceActuator.java | 4 +- .../actuator/FreezeBalanceV2Actuator.java | 4 +- .../actuator/UnDelegateResourceActuator.java | 3 +- .../DelegateResourceProcessor.java | 26 +-- .../FreezeBalanceProcessor.java | 4 +- .../FreezeBalanceV2Processor.java | 5 +- .../UnDelegateResourceProcessor.java | 6 +- .../org/tron/core/vm/utils/FreezeV2Util.java | 40 ++-- .../src/main/java/org/tron/core/Wallet.java | 20 +- .../DelegateResourceActuatorTest.java | 16 +- .../actuator/FreezeBalanceActuatorTest.java | 134 +++++------- .../actuator/FreezeBalanceV2ActuatorTest.java | 75 +++---- .../actuator/UnfreezeBalanceActuatorTest.java | 194 ++++++++---------- .../newaddinterface2/FreezeBalance2Test.java | 2 +- 15 files changed, 234 insertions(+), 327 deletions(-) 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 f91c147e3ee..c1dc9c3758b 100755 --- a/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java @@ -3,6 +3,8 @@ import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; 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.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -136,7 +138,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()) { @@ -152,16 +154,11 @@ public boolean validate() throws ContractValidateException { 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); - - 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; @@ -172,16 +169,11 @@ 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); + 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; @@ -218,6 +210,8 @@ public boolean validate() throws ContractValidateException { return true; } + + @Override public ByteString getOwnerAddress() throws InvalidProtocolBufferException { return any.unpack(DelegateResourceContract.class).getOwnerAddress(); 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..bb1555f502e 100755 --- a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java @@ -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..6b101df6eb9 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; @@ -240,7 +239,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/vm/nativecontract/DelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java index 66ea919d713..bd0b5a941d8 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 9a1af3c9cec..40b26e11fdf 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 2ab9fc451c2..ed23e50abf0 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 f4c18af85e5..88dc88546d8 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 @@ -50,7 +50,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)) { @@ -104,7 +104,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 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..dcc44db262a 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 @@ -1,5 +1,9 @@ package org.tron.core.vm.utils; +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 java.util.List; import java.util.stream.Collectors; @@ -11,8 +15,8 @@ import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; +import org.tron.protos.contract.Common; -import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; public class FreezeV2Util { @@ -163,13 +167,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 +187,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; @@ -250,4 +244,20 @@ private static List getTotalWithdrawList(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)), @@ -1017,10 +996,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(); } } @@ -1099,8 +1076,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); @@ -1123,7 +1100,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(); @@ -1134,16 +1111,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(); } } @@ -1169,16 +1144,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(); } } @@ -1204,16 +1177,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(); } } @@ -1234,13 +1205,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.assertTrue(true); } } diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java index 1253cdc8e0d..4ca463afc33 100644 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java +++ b/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java @@ -87,7 +87,7 @@ public void testFreezeBalance2() { ret1 = freezeBalance2(fromAddress, 999999L, 3L, testKey002); Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be more than 1TRX"); + "Contract validate error : frozenBalance must be greater than or equal to 1 TRX"); //Freeze failed when freeze duration isn't 3 days. ret1 = freezeBalance2(fromAddress, 1000000L, 2L, testKey002); Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); From 28ac9bcb6d71b2cf64ade6f9365c2b5ee46539ba Mon Sep 17 00:00:00 2001 From: chaozhu Date: Mon, 15 May 2023 15:11:51 +0800 Subject: [PATCH 2/3] fix(freezeV2): optimize Stake2.0 code --- .../actuator/DelegateResourceActuator.java | 4 +- .../actuator/FreezeBalanceV2Actuator.java | 2 +- .../actuator/UnfreezeBalanceV2Actuator.java | 16 +- .../org/tron/core/utils/TransactionUtil.java | 37 +++- .../src/main/java/org/tron/core/Wallet.java | 14 +- .../actuator/utils/TransactionUtilTest.java | 206 +++++++++++++++++- 6 files changed, 245 insertions(+), 34 deletions(-) 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 d0efe7c55cf..b8e3ba8585d 100755 --- a/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java @@ -148,8 +148,8 @@ public boolean validate() throws ContractValidateException { long accountNetUsage = ownerCapsule.getNetUsage(); if (null != this.getTx() && this.getTx().isTransactionCreate()) { - accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, - chainBaseManager); + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize( + ownerCapsule.getBalance()); } long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); 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 bb1555f502e..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: 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/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index e5cffa49790..0fec2067b5e 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -253,9 +253,24 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { return tswBuilder.build(); } + public static long estimateConsumeBandWidthSize(long balance) { + DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + long builderSize = builder.build().getSerializedSize(); + + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + long builder2Size = builder2.build().getSerializedSize(); + long addSize = Math.max(builderSize - builder2Size, 0L); + + return DELEGATE_COST_BASE_SIZE + addSize; + } + + // only for testing public static long consumeBandWidthSize( - final TransactionCapsule transactionCapsule, - ChainBaseManager chainBaseManager) { + final TransactionCapsule transactionCapsule, + ChainBaseManager chainBaseManager) { long bytesSize; boolean supportVM = chainBaseManager.getDynamicPropertiesStore().supportVM(); @@ -278,21 +293,21 @@ public static long consumeBandWidthSize( return bytesSize; } - - public static long estimateConsumeBandWidthSize( - final AccountCapsule ownerCapsule, - ChainBaseManager chainBaseManager) { + // only for testing + public static long estimateConsumeBandWidthSizeOld( + final AccountCapsule ownerCapsule, + ChainBaseManager chainBaseManager) { DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + .setLock(true) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build() - , ContractType.DelegateResourceContract); + , ContractType.DelegateResourceContract); long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() - .setBalance(TRX_PRECISION); + .setBalance(TRX_PRECISION); TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build() - , ContractType.DelegateResourceContract); + , ContractType.DelegateResourceContract); long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); long addSize = Math.max(size1 - size2, 0L); diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 9aeec1cf687..dde2aaee0b9 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -780,6 +780,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(); @@ -842,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); @@ -869,7 +867,7 @@ public long calcCanDelegatedBandWidthMaxSize( long accountNetUsage = ownerCapsule.getNetUsage(); accountNetUsage += org.tron.core.utils.TransactionUtil.estimateConsumeBandWidthSize( - ownerCapsule, chainBaseManager); + ownerCapsule.getBalance()); long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); 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 ad8846743e5..5646b30a057 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 @@ -3,29 +3,40 @@ 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.TRX_PRECISION; +import com.google.protobuf.ByteString; import java.nio.charset.StandardCharsets; + import lombok.extern.slf4j.Slf4j; -import org.junit.BeforeClass; +import org.junit.Assert; 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.config.args.Args; import org.tron.core.utils.TransactionUtil; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; @Slf4j(topic = "capsule") public class TransactionUtilTest extends BaseTest { - /** - * Init . - */ - @BeforeClass - public static void init() { - dbPath = "output_transactionUtil_test"; + private static final String dbPath = "output_transactionUtil_test"; + private static final String OWNER_ADDRESS; + + static { + OWNER_ADDRESS = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); } + @Test public void validAccountNameCheck() { String account = ""; @@ -114,4 +125,185 @@ public void isNumberCheck() { assertTrue(isNumber(number.getBytes(StandardCharsets.UTF_8))); } + + + @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 = TransactionUtil.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 = TransactionUtil.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 = TransactionUtil.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 = TransactionUtil.estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); + } + + + @Test + public void testEstimateConsumeBandWidthSizeNew() { + long balance = 1000_000L; + + long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(277, estimateConsumeBandWidthSize1); + + balance = 1000_000_000L; + long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(279, estimateConsumeBandWidthSize2); + + balance = 1000_000_000_000L; + long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(280, estimateConsumeBandWidthSize3); + + balance = 1000_000_000_000_000L; + long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); + } + + + + @Test + public void testEstimateConsumeBandWidthSize() { + dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + 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 = TransactionUtil.estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + + // new value is + estimateConsumeBandWidthSizeNew = TransactionUtil.estimateConsumeBandWidthSize(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() { + long balance = 100; + BalanceContract.DelegateResourceContract.Builder builder = + BalanceContract.DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + BalanceContract.DelegateResourceContract.Builder builder2 = + BalanceContract.DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeBoundary() { + long balance = TRX_PRECISION; + BalanceContract.DelegateResourceContract.Builder builder = + BalanceContract.DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + BalanceContract.DelegateResourceContract.Builder builder2 = + BalanceContract.DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeEdge() { + long balance = TRX_PRECISION + 1; + BalanceContract.DelegateResourceContract.Builder builder = + BalanceContract.DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + BalanceContract.DelegateResourceContract.Builder builder2 = + BalanceContract.DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeCorner() { + long balance = Long.MAX_VALUE; + BalanceContract.DelegateResourceContract.Builder builder = + BalanceContract.DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + BalanceContract.DelegateResourceContract.Builder builder2 = + BalanceContract.DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + Math.max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L); + long actual = TransactionUtil.estimateConsumeBandWidthSize(balance); + Assert.assertEquals(expected, actual); + } + } From 699c0444f0b19c3fd23c7d5258c75d657d19576e Mon Sep 17 00:00:00 2001 From: liuxincheng Date: Fri, 11 Aug 2023 11:07:16 +0800 Subject: [PATCH 3/3] feat(freezeV2): optimize Stake2.0 code --- .../actuator/CancelAllUnfreezeV2Actuator.java | 5 + .../actuator/DelegateResourceActuator.java | 30 ++- .../org/tron/core/utils/ProposalUtil.java | 6 +- .../org/tron/core/utils/TransactionUtil.java | 72 ++----- .../org/tron/core/vm/program/Program.java | 26 ++- .../org/tron/core/vm/utils/FreezeV2Util.java | 1 - .../org/tron/core/db/ResourceProcessor.java | 18 +- .../core/store/DynamicPropertiesStore.java | 6 +- .../java/org/tron/common/utils/JsonUtil.java | 6 +- .../java/org/tron/core/config/Parameter.java | 1 + .../src/main/java/org/tron/core/Wallet.java | 7 +- .../nodepersist/NodePersistService.java | 3 - .../java/org/tron/program/SolidityNode.java | 1 + .../DelegateResourceActuatorTest.java | 22 +- .../actuator/FreezeBalanceActuatorTest.java | 2 +- .../actuator/utils/TransactionUtilTest.java | 196 ++++++++++++------ .../newaddinterface2/FreezeBalance2Test.java | 0 17 files changed, 223 insertions(+), 179 deletions(-) delete mode 100644 framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java 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 6b896654dc7..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,6 +1,7 @@ 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; @@ -66,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 @@ -155,14 +157,12 @@ public boolean validate() throws ContractValidateException { long accountNetUsage = ownerCapsule.getNetUsage(); if (null != this.getTx() && this.getTx().isTransactionCreate()) { - accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize( - ownerCapsule.getBalance()); + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore, + ownerCapsule.getBalance()); } long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); - long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage); - if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) { throw new ContractValidateException( "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance"); @@ -175,9 +175,7 @@ public boolean validate() throws ContractValidateException { long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) (dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); - long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage); - if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) { throw new ContractValidateException( "delegateBalance must be less than or equal to available FreezeEnergyV2 balance"); @@ -211,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( @@ -249,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 " @@ -295,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/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 ac7c6801284..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,71 +254,24 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { return tswBuilder.build(); } - public static long estimateConsumeBandWidthSize(long balance) { - DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(balance); - long builderSize = builder.build().getSerializedSize(); - - DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() - .setBalance(TRX_PRECISION); - long builder2Size = builder2.build().getSerializedSize(); - long addSize = Math.max(builderSize - builder2Size, 0L); - - return DELEGATE_COST_BASE_SIZE + addSize; - } - - // only for testing - 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/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index 13588f6ccdf..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; @@ -557,7 +561,7 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit ownerCapsule.setLatestConsumeTime(now); if (ownerCapsule.getNetUsage() > 0) { bandwidthProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, - ownerCapsule.getNetUsage(), Common.ResourceCode.BANDWIDTH, now); + ownerCapsule.getNetUsage(), BANDWIDTH, now); } EnergyProcessor energyProcessor = @@ -567,7 +571,7 @@ private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inherit ownerCapsule.setLatestConsumeTimeForEnergy(now); if (ownerCapsule.getEnergyUsage() > 0) { energyProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, - ownerCapsule.getEnergyUsage(), Common.ResourceCode.ENERGY, now); + ownerCapsule.getEnergyUsage(), ENERGY, now); } // withdraw expire unfrozen balance @@ -594,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(); } @@ -2077,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; } } @@ -2090,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 112ff205a68..c42973d98ac 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,7 +12,6 @@ import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; - public class FreezeV2Util { private FreezeV2Util() { 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 0ee02e6c10d..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; @@ -134,7 +132,11 @@ public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, } public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiver, - long transferUsage, ResourceCode resourceCode, long now) { + long transferUsage, ResourceCode resourceCode, long now) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now); + return; + } long lastOwnerTime = owner.getLastConsumeTime(resourceCode); long ownerUsage = owner.getUsage(resourceCode); // Update itself first @@ -151,6 +153,7 @@ public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv owner.setNewWindowSize(resourceCode, this.windowSize); owner.setUsage(resourceCode, 0); owner.setLatestTime(resourceCode, now); + return; } // calculate new windowSize long newOwnerWindowSize = getNewWindowSize(ownerUsage, remainOwnerWindowSize, transferUsage, @@ -160,7 +163,7 @@ public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv 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); @@ -170,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); @@ -185,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/common/utils/JsonUtil.java b/common/src/main/java/org/tron/common/utils/JsonUtil.java index ec278712eca..0847e18607b 100644 --- a/common/src/main/java/org/tron/common/utils/JsonUtil.java +++ b/common/src/main/java/org/tron/common/utils/JsonUtil.java @@ -5,8 +5,8 @@ public class JsonUtil { - public static T json2Obj(String jsonString, Class clazz) { - if (StringUtils.hasLength(jsonString) && clazz != null) { + public static final T json2Obj(String jsonString, Class clazz) { + if (!StringUtils.isEmpty(jsonString) && clazz != null) { try { ObjectMapper om = new ObjectMapper(); return om.readValue(jsonString, clazz); @@ -18,7 +18,7 @@ public static T json2Obj(String jsonString, Class clazz) { } } - public static String obj2Json(Object obj) { + public static final String obj2Json(Object obj) { if (obj == null) { return null; } else { 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 efc74b60015..4db83695480 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; @@ -154,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; @@ -193,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; @@ -870,7 +871,7 @@ public long calcCanDelegatedBandWidthMaxSize( processor.updateUsage(ownerCapsule); long accountNetUsage = ownerCapsule.getNetUsage(); - accountNetUsage += org.tron.core.utils.TransactionUtil.estimateConsumeBandWidthSize( + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore, ownerCapsule.getBalance()); long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) @@ -3048,7 +3049,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/main/java/org/tron/core/net/service/nodepersist/NodePersistService.java b/framework/src/main/java/org/tron/core/net/service/nodepersist/NodePersistService.java index 748a4306a12..457fe7c55cb 100644 --- a/framework/src/main/java/org/tron/core/net/service/nodepersist/NodePersistService.java +++ b/framework/src/main/java/org/tron/core/net/service/nodepersist/NodePersistService.java @@ -60,9 +60,6 @@ public List dbRead() { return nodes; } DBNodes dbNodes = JsonUtil.json2Obj(new String(nodeBytes), DBNodes.class); - if (Objects.isNull(dbNodes)) { - return nodes; - } logger.info("Read node from store: {} nodes", dbNodes.getNodes().size()); dbNodes.getNodes().forEach(n -> nodes.add(new InetSocketAddress(n.getHost(), n.getPort()))); } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index 491c9e8a6ff..0ca001da7bb 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -8,6 +8,7 @@ import org.apache.commons.lang3.BooleanUtils; import org.springframework.context.ApplicationContext; import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; 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 7bffaa78a1c..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,7 @@ public void testDelegateResourceWithNoFreeze() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { @@ -193,7 +195,7 @@ public void testDelegateResourceWithNoFreeze() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { @@ -223,7 +225,7 @@ public void testDelegateBandwidthWithUsage() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { @@ -253,7 +255,7 @@ public void testDelegateCpuWithUsage() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { @@ -409,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); @@ -664,7 +666,7 @@ public void delegateLessThanZero() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("delegateBalance must be greater than or equal to 1 TRX", + assertEquals("delegateBalance must be greater than or equal to 1 TRX", e.getMessage()); } catch (ContractExeException e) { fail(e.getMessage()); @@ -703,7 +705,7 @@ public void delegateMoreThanBalance() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { 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 91d660073cf..c66a86fe58c 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java @@ -501,7 +501,7 @@ public void invalidOwnerAddress() { } catch (ContractValidateException e) { Assert.assertEquals("Invalid address", e.getMessage()); } catch (ContractExeException e) { - Assert.assertTrue(true); + Assert.fail(); } } 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 6dba1d56e68..c3ff9243f66 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,35 +4,37 @@ 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; import static org.tron.core.utils.TransactionUtil.validTokenAbbrName; -import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; -import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; 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.Assert; import org.junit.Test; import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -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.AccountType; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; import org.tron.protos.Protocol; -import org.tron.protos.contract.BalanceContract; - +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; @Slf4j(topic = "capsule") public class TransactionUtilTest extends BaseTest { @@ -47,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 @@ -63,6 +64,80 @@ public void setUp() { dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); } + // only for testing + 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() == Transaction.Contract.ContractType.ShieldedTransferContract) { + continue; + } + if (supportVM) { + bytesSize += Constant.MAX_RESULT_SIZE_IN_TX; + } + } + + return bytesSize; + } + + // 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() { @@ -74,7 +149,6 @@ public void validAccountNameCheck() { assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); account.append('z'); assertFalse(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); - } @Test @@ -156,7 +230,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); @@ -168,18 +242,17 @@ 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(); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); long balance = 1000_000L; AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), @@ -188,7 +261,7 @@ public void testEstimateConsumeBandWidthSizeOld() { ownerCapsule.addFrozenBalanceForBandwidthV2(balance); dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); ownerCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSizeOld( + long estimateConsumeBandWidthSize1 = estimateConsumeBandWidthSizeOld( ownerCapsule, chainBaseManager); Assert.assertEquals(277, estimateConsumeBandWidthSize1); @@ -198,7 +271,7 @@ public void testEstimateConsumeBandWidthSizeOld() { balance); ownerCapsule.addFrozenBalanceForBandwidthV2(balance); dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); - long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSizeOld( + long estimateConsumeBandWidthSize2 = estimateConsumeBandWidthSizeOld( ownerCapsule, chainBaseManager); Assert.assertEquals(279, estimateConsumeBandWidthSize2); @@ -208,7 +281,7 @@ public void testEstimateConsumeBandWidthSizeOld() { balance); ownerCapsule.addFrozenBalanceForBandwidthV2(balance); dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); - long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSizeOld( + long estimateConsumeBandWidthSize3 = estimateConsumeBandWidthSizeOld( ownerCapsule, chainBaseManager); Assert.assertEquals(280, estimateConsumeBandWidthSize3); @@ -218,7 +291,7 @@ public void testEstimateConsumeBandWidthSizeOld() { balance); ownerCapsule.addFrozenBalanceForBandwidthV2(balance); dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); - long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSizeOld( + long estimateConsumeBandWidthSize4 = estimateConsumeBandWidthSizeOld( ownerCapsule, chainBaseManager); Assert.assertEquals(282, estimateConsumeBandWidthSize4); } @@ -227,29 +300,29 @@ public void testEstimateConsumeBandWidthSizeOld() { @Test public void testEstimateConsumeBandWidthSizeNew() { long balance = 1000_000L; - - long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSize(balance); + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(277, estimateConsumeBandWidthSize1); balance = 1000_000_000L; - long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSize(balance); + long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(279, estimateConsumeBandWidthSize2); balance = 1000_000_000_000L; - long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSize(balance); + long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(280, estimateConsumeBandWidthSize3); balance = 1000_000_000_000_000L; - long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSize(balance); + long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(282, estimateConsumeBandWidthSize4); } - @Test public void testEstimateConsumeBandWidthSize3() { dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); - ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); long balance = 1000_000L; AccountCapsule ownerCapsule; @@ -263,11 +336,11 @@ public void testEstimateConsumeBandWidthSize3() { balance); ownerCapsule.addFrozenBalanceForBandwidthV2(balance); dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); - estimateConsumeBandWidthSizeOld = TransactionUtil.estimateConsumeBandWidthSizeOld( + estimateConsumeBandWidthSizeOld = estimateConsumeBandWidthSizeOld( ownerCapsule, chainBaseManager); // new value is - estimateConsumeBandWidthSizeNew = TransactionUtil.estimateConsumeBandWidthSize(balance); + estimateConsumeBandWidthSizeNew = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); System.out.println("balance:" + balance @@ -289,70 +362,73 @@ public void testEstimateConsumeBandWidthSize3() { @Test public void estimateConsumeBandWidthSizePositive() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); long balance = 100; - BalanceContract.DelegateResourceContract.Builder builder = - BalanceContract.DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(balance); - BalanceContract.DelegateResourceContract.Builder builder2 = - BalanceContract.DelegateResourceContract.newBuilder() - .setBalance(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(balance); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); } @Test public void estimateConsumeBandWidthSizeBoundary() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); long balance = TRX_PRECISION; - BalanceContract.DelegateResourceContract.Builder builder = - BalanceContract.DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(balance); - BalanceContract.DelegateResourceContract.Builder builder2 = - BalanceContract.DelegateResourceContract.newBuilder() - .setBalance(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(balance); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); } @Test public void estimateConsumeBandWidthSizeEdge() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); long balance = TRX_PRECISION + 1; - BalanceContract.DelegateResourceContract.Builder builder = - BalanceContract.DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(balance); - BalanceContract.DelegateResourceContract.Builder builder2 = - BalanceContract.DelegateResourceContract.newBuilder() - .setBalance(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(balance); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); } @Test public void estimateConsumeBandWidthSizeCorner() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); long balance = Long.MAX_VALUE; - BalanceContract.DelegateResourceContract.Builder builder = - BalanceContract.DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(balance); - BalanceContract.DelegateResourceContract.Builder builder2 = - BalanceContract.DelegateResourceContract.newBuilder() - .setBalance(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(balance); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); Assert.assertEquals(expected, actual); } - } diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java deleted file mode 100644 index e69de29bb2d..00000000000